Skip to content
Source
Sign inSign up
Open History to see the last commit

HttpApiTransformer.ts

559 lines17.9 KB

1/**
2 * Renders parsed OpenAPI operations into generated Effect HttpApi source code.
3 *
4 * This module maps normalized OpenAPI metadata, tags, request bodies,
5 * responses, and security requirements into import declarations, HttpApi
6 * groups, endpoint definitions, schema annotations, and middleware classes.
7 * The rendered TypeScript can be emitted by the OpenAPI generator as an
8 * executable Effect `HttpApi` module.
9 *
10 * @since 4.0.0
11 */
12import type {
13 ParsedOpenApi,
14 ParsedOpenApiSecurityScheme,
15 ParsedOpenApiTag,
16 ParsedOperation,
17 ParsedOperationMediaTypeSchema,
18 ParsedOperationResponse
19} from "./ParsedOperation.ts"
20import * as Utils from "./Utils.ts"
21​
22interface GroupRenderModel {
23 readonly identifier: string
24 readonly topLevel: boolean
25 readonly metadata: ParsedOpenApiTag | undefined
26 readonly operations: ReadonlyArray<ParsedOperation>
27 readonly constName: string
29​
30interface SecurityRenderModel {
31 readonly securityDeclarations: ReadonlyArray<string>
32 readonly middlewareDeclarations: ReadonlyArray<string>
33 readonly endpointMiddlewares: ReadonlyMap<string, ReadonlyArray<string>>
35​
36const fallbackGroupIdentifier = "default"
37​
38/**
39 * Render the import declarations required by generated HttpApi source.
40 *
41 * **Details**
42 *
43 * The schema namespace import is named by the caller so generated code can
44 * avoid collisions with symbols already present in the output module. Multipart
45 * support is included only when the parsed OpenAPI document needs it.
46 *
47 * @category code generation
48 * @since 4.0.0
49 */
50export const imports = (
51 importName: string,
52 options?: {
53 readonly multipart?: boolean | undefined
54 }
55): string =>
56 [
57 `import * as ${importName} from "effect/Schema"`,
58 ...(options?.multipart === true ? [`import { Multipart } from "effect/http"`] : []),
59 `import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, HttpApiSecurity, OpenApi } from "effect/http-api"`
60 ].join("\n")
61​
62/**
63 * Convert a parsed OpenAPI document into Effect HttpApi source code.
64 *
65 * **Details**
66 *
67 * The generated implementation contains security declarations, reusable
68 * middleware classes, HttpApi groups, endpoint definitions, and OpenAPI
69 * annotations derived from the parsed operation metadata.
70 *
71 * @category code generation
72 * @since 4.0.0
73 */
74export const toImplementation = (
75 _importName: string,
76 name: string,
77 parsed: ParsedOpenApi
78): string => {
79 const security = buildSecurityRenderModel(parsed)
80 const groups = groupOperations(parsed)
81 const groupSources = groups.map((group) => renderGroup(group, security.endpointMiddlewares))
82 const metadataAnnotations = renderApiAnnotations(parsed)
83​
84 let apiValue = `export class ${name} extends HttpApi.make(${JSON.stringify(name)})`
85 for (const annotation of metadataAnnotations) {
86 apiValue += `\n .${annotation}`
87 }
88 if (groups.length > 0) {
89 apiValue += `\n .add(${groups.map((group) => group.constName).join(", ")})`
90 }
91 apiValue += ` {}`
92​
93 return [
94 ...security.securityDeclarations,
95 ...security.middlewareDeclarations,
96 ...groupSources,
97 apiValue
98 ].join("\n\n")
100​
101const groupOperations = (parsed: ParsedOpenApi): ReadonlyArray<GroupRenderModel> => {
102 const tagMetadata = new Map(parsed.tags.map((tag) => [tag.name, tag]))
103 const byIdentifier = new Map<string, {
104 readonly identifier: string
105 topLevel: boolean
106 readonly metadata: ParsedOpenApiTag | undefined
107 readonly operations: Array<ParsedOperation>
108 }>()
109​
110 for (const operation of parsed.operations) {
111 const identifier = operation.tags[0] ?? fallbackGroupIdentifier
112 const topLevel = operation.tags.length === 0
113 const existing = byIdentifier.get(identifier)
114 if (existing) {
115 if (topLevel) {
116 existing.topLevel = true
117 }
118 existing.operations.push(operation)
119 continue
120 }
121 byIdentifier.set(identifier, {
122 identifier,
123 topLevel,
124 metadata: tagMetadata.get(identifier),
125 operations: [operation]
126 })
127 }
128​
129 const allocateName = makeNameAllocator()
130 const groups: Array<GroupRenderModel> = []
131 for (const group of byIdentifier.values()) {
132 const baseName = ensureIdentifier(group.identifier, "Group")
133 groups.push({
134 ...group,
135 constName: allocateName(`${baseName}Group`)
136 })
137 }
138 return groups
140​
141const renderGroup = (
142 group: GroupRenderModel,
143 endpointMiddlewares: ReadonlyMap<string, ReadonlyArray<string>>
144): string => {
145 let source = `class ${group.constName} extends HttpApiGroup.make(${JSON.stringify(group.identifier)}${
146 group.topLevel ? ", { topLevel: true }" : ""
147 })`
148​
149 const allocateEndpointName = makeNameAllocator()
150 const endpointSources = group.operations.map((operation) =>
151 renderEndpoint(
152 operation,
153 allocateEndpointName(operation.id),
154 endpointMiddlewares.get(toOperationKey(operation)) ?? []
155 )
156 )
157 if (endpointSources.length > 0) {
158 source += `\n .add(${endpointSources.join(", \n ")})`
159 }
160​
161 if (group.metadata?.description !== undefined) {
162 source += `\n .annotate(OpenApi.Description, ${JSON.stringify(group.metadata.description)})`
163 }
164 if (group.metadata?.externalDocs !== undefined) {
165 source += `\n .annotate(OpenApi.ExternalDocs, ${JSON.stringify(group.metadata.externalDocs)})`
166 }
167​
168 source += ` {}`
169​
170 return source
172​
173const renderEndpoint = (
174 operation: ParsedOperation,
175 endpointName: string,
176 endpointMiddlewares: ReadonlyArray<string>
177): string => {
178 const options: Array<string> = []
179 if (operation.pathSchema !== undefined) {
180 options.push(`params: ${operation.pathSchema}`)
181 }
182 if (operation.querySchema !== undefined) {
183 options.push(`query: ${operation.querySchema}`)
184 }
185 if (operation.headersSchema !== undefined) {
186 options.push(`headers: ${operation.headersSchema}`)
187 }
188​
189 const payload = renderPayload(operation)
190 if (payload !== undefined) {
191 options.push(`payload: ${payload}`)
192 }
193​
194 const success = renderResponseSet(operation.responses, "success")
195 if (success !== undefined) {
196 options.push(`success: ${success}`)
197 }
198​
199 const error = renderResponseSet(operation.responses, "error")
200 if (error !== undefined) {
201 options.push(`error: ${error}`)
202 }
203​
204 const endpoint = options.length === 0
205 ? `HttpApiEndpoint.${operation.method}(${JSON.stringify(endpointName)}, ${
206 JSON.stringify(toHttpApiPath(operation.path))
207 })`
208 : `HttpApiEndpoint.${operation.method}(${JSON.stringify(endpointName)}, ${
209 JSON.stringify(toHttpApiPath(operation.path))
210 }, { ${options.join(", ")} })`
211​
212 const annotations: Array<string> = []
213 if (operation.operationId !== undefined) {
214 annotations.push(`annotate(OpenApi.Identifier, ${JSON.stringify(operation.operationId)})`)
215 }
216 if (operation.metadata.summary !== undefined) {
217 annotations.push(`annotate(OpenApi.Summary, ${JSON.stringify(operation.metadata.summary)})`)
218 }
219 if (operation.metadata.description !== undefined) {
220 annotations.push(`annotate(OpenApi.Description, ${JSON.stringify(operation.metadata.description)})`)
221 }
222 if (operation.metadata.deprecated) {
223 annotations.push(`annotate(OpenApi.Deprecated, true)`)
224 }
225 if (operation.metadata.externalDocs !== undefined) {
226 annotations.push(`annotate(OpenApi.ExternalDocs, ${JSON.stringify(operation.metadata.externalDocs)})`)
227 }
228​
229 if (annotations.length === 0 && endpointMiddlewares.length === 0) {
230 return endpoint
231 }
232​
233 let out = endpoint
234 for (const middleware of endpointMiddlewares) {
235 out += `\n .middleware(${middleware})`
236 }
237 for (const annotation of annotations) {
238 out += `\n .${annotation}`
239 }
240 return out
242​
243const renderPayload = (operation: ParsedOperation): string | undefined => {
244 if (!methodSupportsBody(operation.method)) {
245 return
246 }
247 const payloads = operation.requestBodyRepresentable.map((schema) => renderMediaSchema(schema))
248 if (payloads.length === 0) {
249 return
250 }
251​
252 if (operation.requestBody?.required === false) {
253 payloads.unshift("HttpApiSchema.NoContent")
254 }
255​
256 return joinSchemas(payloads)
258​
259const renderResponseSet = (
260 responses: ReadonlyArray<ParsedOperationResponse>,
261 target: "success" | "error"
262): string | undefined => {
263 const rendered: Array<string> = []
264​
265 for (const response of responses) {
266 const status = toStatus(response.status)
267 if (status === undefined) {
268 continue
269 }
270​
271 const isSuccess = status < 400
272 if ((target === "success") !== isSuccess) {
273 continue
274 }
275​
276 if (response.isEmpty) {
277 rendered.push(`HttpApiSchema.Empty(${status})`)
278 continue
279 }
280​
281 for (const media of response.representable) {
282 rendered.push(applyStatus(renderMediaSchema(media), status, target))
283 }
284 }
285​
286 if (rendered.length === 0) {
287 return
288 }
289​
290 return joinSchemas(rendered)
292​
293const joinSchemas = (schemas: ReadonlyArray<string>): string =>
294 schemas.length === 1 ? schemas[0] : `[${schemas.join(", ")}]`
295​
296const renderMediaSchema = (media: ParsedOperationMediaTypeSchema): string => {
297 if (media.effectStream === "sse") {
298 const options = media.contentType === "text/event-stream"
299 ? `{ events: ${media.schema}, error: ${media.errorSchema} }`
300 : `{ contentType: ${JSON.stringify(media.contentType)}, events: ${media.schema}, error: ${media.errorSchema} }`
301 return `HttpApiSchema.StreamSse(${options})`
302 }
303​
304 if (media.effectStream === "uint8array") {
305 if (media.contentType === "application/octet-stream") {
306 return "HttpApiSchema.StreamUint8Array()"
307 }
308 return `HttpApiSchema.StreamUint8Array({ contentType: ${JSON.stringify(media.contentType)} })`
309 }
310​
311 if (media.effectStream === "ndjson") {
312 if (media.contentType === "application/x-ndjson") {
313 return `HttpApiSchema.StreamNdjson({ schema: ${media.schema} })`
314 }
315 return `HttpApiSchema.StreamNdjson({ schema: ${media.schema}, contentType: ${JSON.stringify(media.contentType)} })`
316 }
317​
318 switch (media.encoding) {
319 case "json": {
320 if (media.contentType === "application/json") {
321 return media.schema
322 }
323 return `${media.schema}.pipe(HttpApiSchema.asJson({ contentType: ${JSON.stringify(media.contentType)} }))`
324 }
325 case "multipart": {
326 return `${media.schema}.pipe(HttpApiSchema.asMultipart())`
327 }
328 case "form-url-encoded": {
329 if (media.contentType === "application/x-www-form-urlencoded") {
330 return `${media.schema}.pipe(HttpApiSchema.asFormUrlEncoded())`
331 }
332 return `${media.schema}.pipe(HttpApiSchema.asFormUrlEncoded({ contentType: ${
333 JSON.stringify(media.contentType)
334 } }))`
335 }
336 case "text": {
337 if (media.contentType === "text/plain") {
338 return `${media.schema}.pipe(HttpApiSchema.asText())`
339 }
340 return `${media.schema}.pipe(HttpApiSchema.asText({ contentType: ${JSON.stringify(media.contentType)} }))`
341 }
342 case "binary": {
343 if (media.contentType === "application/octet-stream") {
344 return `${media.schema}.pipe(HttpApiSchema.asUint8Array())`
345 }
346 return `${media.schema}.pipe(HttpApiSchema.asUint8Array({ contentType: ${JSON.stringify(media.contentType)} }))`
347 }
348 }
350​
351const renderApiAnnotations = (parsed: ParsedOpenApi): ReadonlyArray<string> => {
352 const annotations: Array<string> = [
353 `annotate(OpenApi.Title, ${JSON.stringify(parsed.metadata.title)})`,
354 `annotate(OpenApi.Version, ${JSON.stringify(parsed.metadata.version)})`
355 ]
356​
357 if (parsed.metadata.summary !== undefined) {
358 annotations.push(`annotate(OpenApi.Summary, ${JSON.stringify(parsed.metadata.summary)})`)
359 }
360 if (parsed.metadata.description !== undefined) {
361 annotations.push(`annotate(OpenApi.Description, ${JSON.stringify(parsed.metadata.description)})`)
362 }
363 if (parsed.metadata.license !== undefined) {
364 annotations.push(`annotate(OpenApi.License, ${JSON.stringify(parsed.metadata.license)})`)
365 }
366 if (parsed.metadata.servers !== undefined) {
367 annotations.push(`annotate(OpenApi.Servers, ${JSON.stringify(parsed.metadata.servers)})`)
368 }
369​
370 return annotations
372​
373const buildSecurityRenderModel = (parsed: ParsedOpenApi): SecurityRenderModel => {
374 const allocateName = makeNameAllocator()
375 const securityDeclarations: Array<string> = []
376 const middlewareDeclarations: Array<string> = []
377 const endpointMiddlewares = new Map<string, ReadonlyArray<string>>()
378 const schemeDeclarations = new Map<string, string>()
379 const middlewareNames = new Map<string, string>()
380​
381 for (const securityScheme of parsed.securitySchemes) {
382 const baseName = ensureIdentifier(securityScheme.name, "Security")
383 const declarationName = allocateName(`${baseName}Security`)
384 schemeDeclarations.set(securityScheme.name, declarationName)
385 securityDeclarations.push(`export const ${declarationName} = ${renderSecurityScheme(securityScheme)}`)
386 }
387​
388 for (const operation of parsed.operations) {
389 if (operation.effectiveSecurity.length === 0) {
390 continue
391 }
392 if (operation.effectiveSecurity.some((requirement) => Object.keys(requirement).length === 0)) {
393 continue
394 }
395​
396 const operationMiddlewareNames: Array<string> = []
397 const seenOrSchemes = new Set<string>()
398 const andRequirements: Array<ReadonlyArray<string>> = []
399​
400 for (const requirement of operation.effectiveSecurity) {
401 const schemes = Object.keys(requirement)
402 if (schemes.length === 1) {
403 const schemeName = schemes[0]
404 if (schemeDeclarations.has(schemeName) && !seenOrSchemes.has(schemeName)) {
405 seenOrSchemes.add(schemeName)
406 }
407 } else if (schemes.length > 1) {
408 andRequirements.push([...schemes].sort())
409 }
410 }
411​
412 const orSchemeNames = Array.from(seenOrSchemes).sort()
413 if (orSchemeNames.length > 0) {
414 const className = getOrSecurityMiddlewareName(orSchemeNames)
415 operationMiddlewareNames.push(className)
416 }
417​
418 const seenAndRequirements = new Set<string>()
419 for (const requirement of andRequirements) {
420 const key = requirement.join("\u0000")
421 if (seenAndRequirements.has(key)) {
422 continue
423 }
424 seenAndRequirements.add(key)
425 const className = getAndSecurityMiddlewareName(requirement)
426 operationMiddlewareNames.push(className)
427 }
428​
429 if (operationMiddlewareNames.length > 0) {
430 endpointMiddlewares.set(toOperationKey(operation), operationMiddlewareNames)
431 }
432 }
433​
434 return {
435 securityDeclarations,
436 middlewareDeclarations,
437 endpointMiddlewares
438 }
439​
440 function getOrSecurityMiddlewareName(schemes: ReadonlyArray<string>): string {
441 const key = `or:${schemes.join("\u0000")}`
442 const existing = middlewareNames.get(key)
443 if (existing !== undefined) {
444 return existing
445 }
446​
447 const className = allocateName(`${getSecurityMiddlewareBaseName(schemes, "Or")}SecurityMiddleware`)
448 const securityEntries = schemes.map((name) => `${JSON.stringify(name)}: ${schemeDeclarations.get(name)!}`).join(
449 ", "
450 )
451 middlewareDeclarations.push(
452 `export class ${className} extends HttpApiMiddleware.Service<${className}>()(${
453 JSON.stringify(`${schemes.join(" | ")} security`)
454 }, { security: { ${securityEntries} } }) {}`
455 )
456 middlewareNames.set(key, className)
457 return className
458 }
459​
460 function getAndSecurityMiddlewareName(schemes: ReadonlyArray<string>): string {
461 const key = `and:${schemes.join("\u0000")}`
462 const existing = middlewareNames.get(key)
463 if (existing !== undefined) {
464 return existing
465 }
466​
467 const className = allocateName(`${getSecurityMiddlewareBaseName(schemes, "And")}SecurityMiddleware`)
468 middlewareDeclarations.push(
469 `class ${className} extends HttpApiMiddleware.Service<${className}>()(${
470 JSON.stringify(`${schemes.join(" & ")} security`)
471 }) {}`
472 )
473 middlewareNames.set(key, className)
474 return className
475 }
477​
478const getSecurityMiddlewareBaseName = (
479 schemes: ReadonlyArray<string>,
480 joiner: "And" | "Or"
481): string => {
482 const [head, ...tail] = schemes.map((scheme) => ensureIdentifier(scheme, "Security"))
483 return tail.length === 0 ? head : [head, ...tail.map((scheme) => `${joiner}${scheme}`)].join("")
485​
486const renderSecurityScheme = (securityScheme: ParsedOpenApiSecurityScheme): string => {
487 let source: string
488 switch (securityScheme.type) {
489 case "basic": {
490 source = "HttpApiSecurity.basic"
491 break
492 }
493 case "bearer": {
494 source = "HttpApiSecurity.bearer"
495 break
496 }
497 case "http": {
498 source = `HttpApiSecurity.http({ scheme: ${JSON.stringify(securityScheme.scheme!)} })`
499 break
500 }
501 case "apiKey": {
502 source = `HttpApiSecurity.apiKey({ key: ${JSON.stringify(securityScheme.key!)}, in: ${
503 JSON.stringify(securityScheme.in!)
504 } })`
505 break
506 }
507 }
508​
509 if (securityScheme.description !== undefined) {
510 source += `.pipe(HttpApiSecurity.annotate(OpenApi.Description, ${JSON.stringify(securityScheme.description)}))`
511 }
512 if (
513 (securityScheme.type === "bearer" || securityScheme.type === "http") && securityScheme.bearerFormat !== undefined
514 ) {
515 source += `.pipe(HttpApiSecurity.annotate(OpenApi.Format, ${JSON.stringify(securityScheme.bearerFormat)}))`
516 }
517​
518 return source
520​
521const toOperationKey = (operation: ParsedOperation): string => `${operation.method}:${operation.path}`
522​
523const toHttpApiPath = (path: string): string => path.replace(/{([^}]+)}/g, ":$1")
524​
525const toStatus = (status: string): number | undefined => {
526 if (!/^\d{3}$/.test(status)) {
527 return
528 }
529 return Number(status)
531​
532const applyStatus = (schema: string, status: number, target: "success" | "error"): string => {
533 if ((target === "success" && status === 200) || (target === "error" && status === 500)) {
534 return schema
535 }
536 return `${schema}.pipe(HttpApiSchema.status(${status}))`
538​
539const methodSupportsBody = (method: ParsedOperation["method"]): boolean =>
540 method !== "get" && method !== "head" && method !== "options" && method !== "trace"
541​
542const ensureIdentifier = (value: string, fallback: string): string => {
543 const sanitized = Utils.identifier(value)
544 return sanitized.length > 0 ? sanitized : fallback
546​
547const makeNameAllocator = () => {
548 const used = new Set<string>()
549 return (base: string) => {
550 let candidate = base
551 let index = 2
552 while (used.has(candidate)) {
553 candidate = `${base}${index}`
554 index += 1
555 }
556 used.add(candidate)
557 return candidate
558 }