UNPKG

@orpc/openapi

Version:

<div align="center"> <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 alt="oRPC logo" /> </div>

752 lines (742 loc) • 26.5 kB
import { isORPCErrorStatus, fallbackORPCErrorStatus, fallbackORPCErrorMessage } from '@orpc/client'; import { toHttpPath } from '@orpc/client/standard'; import { fallbackContractConfig, getEventIteratorSchemaDetails } from '@orpc/contract'; import { standardizeHTTPPath, StandardOpenAPIJsonSerializer, getDynamicParams } from '@orpc/openapi-client/standard'; import { isProcedure, resolveContractProcedures } from '@orpc/server'; import { isObject, stringifyJSON, findDeepMatches, toArray, clone, value } from '@orpc/shared'; import { TypeName } from '@orpc/interop/json-schema-typed/draft-2020-12'; const OPERATION_EXTENDER_SYMBOL = Symbol("ORPC_OPERATION_EXTENDER"); function customOpenAPIOperation(o, extend) { return new Proxy(o, { get(target, prop, receiver) { if (prop === OPERATION_EXTENDER_SYMBOL) { return extend; } return Reflect.get(target, prop, receiver); } }); } function getCustomOpenAPIOperation(o) { return o[OPERATION_EXTENDER_SYMBOL]; } function applyCustomOpenAPIOperation(operation, contract) { const operationCustoms = []; for (const errorItem of Object.values(contract["~orpc"].errorMap)) { const maybeExtender = errorItem ? getCustomOpenAPIOperation(errorItem) : void 0; if (maybeExtender) { operationCustoms.push(maybeExtender); } } if (isProcedure(contract)) { for (const middleware of contract["~orpc"].middlewares) { const maybeExtender = getCustomOpenAPIOperation(middleware); if (maybeExtender) { operationCustoms.push(maybeExtender); } } } let currentOperation = operation; for (const custom of operationCustoms) { if (typeof custom === "function") { currentOperation = custom(currentOperation, contract); } else { currentOperation = { ...currentOperation, ...custom }; } } return currentOperation; } const LOGIC_KEYWORDS = [ "$dynamicRef", "$ref", "additionalItems", "additionalProperties", "allOf", "anyOf", "const", "contains", "contentEncoding", "contentMediaType", "contentSchema", "dependencies", "dependentRequired", "dependentSchemas", "else", "enum", "exclusiveMaximum", "exclusiveMinimum", "format", "if", "items", "maxContains", "maximum", "maxItems", "maxLength", "maxProperties", "minContains", "minimum", "minItems", "minLength", "minProperties", "multipleOf", "not", "oneOf", "pattern", "patternProperties", "prefixItems", "properties", "propertyNames", "required", "then", "type", "unevaluatedItems", "unevaluatedProperties", "uniqueItems" ]; function isFileSchema(schema) { return isObject(schema) && schema.type === "string" && typeof schema.contentMediaType === "string"; } function isObjectSchema(schema) { return isObject(schema) && schema.type === "object"; } function isAnySchema(schema) { if (schema === true) { return true; } if (Object.keys(schema).every((k) => !LOGIC_KEYWORDS.includes(k))) { return true; } return false; } function separateObjectSchema(schema, separatedProperties) { if (Object.keys(schema).some( (k) => !["type", "properties", "required", "additionalProperties"].includes(k) && LOGIC_KEYWORDS.includes(k) && schema[k] !== void 0 )) { return [{ type: "object" }, schema]; } const matched = { ...schema }; const rest = { ...schema }; matched.properties = separatedProperties.reduce((acc, key) => { const keySchema = schema.properties?.[key] ?? schema.additionalProperties; if (keySchema !== void 0) { acc[key] = keySchema; } return acc; }, {}); matched.required = schema.required?.filter((key) => separatedProperties.includes(key)); matched.examples = schema.examples?.map((example) => { if (!isObject(example)) { return example; } return Object.entries(example).reduce((acc, [key, value]) => { if (separatedProperties.includes(key)) { acc[key] = value; } return acc; }, {}); }); rest.properties = schema.properties && Object.entries(schema.properties).filter(([key]) => !separatedProperties.includes(key)).reduce((acc, [key, value]) => { acc[key] = value; return acc; }, {}); rest.required = schema.required?.filter((key) => !separatedProperties.includes(key)); rest.examples = schema.examples?.map((example) => { if (!isObject(example)) { return example; } return Object.entries(example).reduce((acc, [key, value]) => { if (!separatedProperties.includes(key)) { acc[key] = value; } return acc; }, {}); }); return [matched, rest]; } function filterSchemaBranches(schema, check, matches = []) { if (check(schema)) { matches.push(schema); return [matches, void 0]; } if (isObject(schema)) { for (const keyword of ["anyOf", "oneOf"]) { if (schema[keyword] && Object.keys(schema).every( (k) => k === keyword || !LOGIC_KEYWORDS.includes(k) )) { const rest = schema[keyword].map((s) => filterSchemaBranches(s, check, matches)[1]).filter((v) => !!v); if (rest.length === 1 && typeof rest[0] === "object") { return [matches, { ...schema, [keyword]: void 0, ...rest[0] }]; } return [matches, { ...schema, [keyword]: rest }]; } } } return [matches, schema]; } function applySchemaOptionality(required, schema) { if (required) { return schema; } return { anyOf: [ schema, { not: {} } ] }; } function expandUnionSchema(schema) { if (typeof schema === "object") { for (const keyword of ["anyOf", "oneOf"]) { if (schema[keyword] && Object.keys(schema).every( (k) => k === keyword || !LOGIC_KEYWORDS.includes(k) )) { return schema[keyword].flatMap((s) => expandUnionSchema(s)); } } } return [schema]; } function expandArrayableSchema(schema) { const schemas = expandUnionSchema(schema); if (schemas.length !== 2) { return void 0; } const arraySchema = schemas.find( (s) => typeof s === "object" && s.type === "array" && Object.keys(s).filter((k) => LOGIC_KEYWORDS.includes(k)).every((k) => k === "type" || k === "items") ); if (arraySchema === void 0) { return void 0; } const items1 = arraySchema.items; const items2 = schemas.find((s) => s !== arraySchema); if (stringifyJSON(items1) !== stringifyJSON(items2)) { return void 0; } return [items2, arraySchema]; } const PRIMITIVE_SCHEMA_TYPES = /* @__PURE__ */ new Set([ TypeName.String, TypeName.Number, TypeName.Integer, TypeName.Boolean, TypeName.Null ]); function isPrimitiveSchema(schema) { return expandUnionSchema(schema).every((s) => { if (typeof s === "boolean") { return false; } if (typeof s.type === "string" && PRIMITIVE_SCHEMA_TYPES.has(s.type)) { return true; } if (s.const !== void 0) { return true; } return false; }); } function toOpenAPIPath(path) { return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/{$1}"); } function toOpenAPIMethod(method) { return method.toLocaleLowerCase(); } function toOpenAPIContent(schema) { const content = {}; const [matches, restSchema] = filterSchemaBranches(schema, isFileSchema); for (const file of matches) { content[file.contentMediaType] = { schema: toOpenAPISchema(file) }; } if (restSchema !== void 0) { content["application/json"] = { schema: toOpenAPISchema(restSchema) }; const isStillHasFileSchema = findDeepMatches((v) => isObject(v) && isFileSchema(v), restSchema).values.length > 0; if (isStillHasFileSchema) { content["multipart/form-data"] = { schema: toOpenAPISchema(restSchema) }; } } return content; } function toOpenAPIEventIteratorContent([yieldsRequired, yieldsSchema], [returnsRequired, returnsSchema]) { return { "text/event-stream": { schema: toOpenAPISchema({ oneOf: [ { type: "object", properties: { event: { const: "message" }, data: yieldsSchema, id: { type: "string" }, retry: { type: "number" } }, required: yieldsRequired ? ["event", "data"] : ["event"] }, { type: "object", properties: { event: { const: "done" }, data: returnsSchema, id: { type: "string" }, retry: { type: "number" } }, required: returnsRequired ? ["event", "data"] : ["event"] }, { type: "object", properties: { event: { const: "error" }, data: {}, id: { type: "string" }, retry: { type: "number" } }, required: ["event"] } ] }) } }; } function toOpenAPIParameters(schema, parameterIn) { const parameters = []; for (const key in schema.properties) { const keySchema = schema.properties[key]; let isDeepObjectStyle = true; if (parameterIn !== "query") { isDeepObjectStyle = false; } else if (isPrimitiveSchema(keySchema)) { isDeepObjectStyle = false; } else { const [item] = expandArrayableSchema(keySchema) ?? []; if (item !== void 0 && isPrimitiveSchema(item)) { isDeepObjectStyle = false; } } parameters.push({ name: key, in: parameterIn, required: schema.required?.includes(key), schema: toOpenAPISchema(keySchema), style: isDeepObjectStyle ? "deepObject" : void 0, explode: isDeepObjectStyle ? true : void 0, allowEmptyValue: parameterIn === "query" ? true : void 0, allowReserved: parameterIn === "query" ? true : void 0 }); } return parameters; } function checkParamsSchema(schema, params) { const properties = Object.keys(schema.properties ?? {}); const required = schema.required ?? []; if (properties.length !== params.length || properties.some((v) => !params.includes(v))) { return false; } if (required.length !== params.length || required.some((v) => !params.includes(v))) { return false; } return true; } function toOpenAPISchema(schema) { return schema === true ? {} : schema === false ? { not: {} } : schema; } const OPENAPI_JSON_SCHEMA_REF_PREFIX = "#/components/schemas/"; function resolveOpenAPIJsonSchemaRef(doc, schema) { if (typeof schema !== "object" || !schema.$ref?.startsWith(OPENAPI_JSON_SCHEMA_REF_PREFIX)) { return schema; } const name = schema.$ref.slice(OPENAPI_JSON_SCHEMA_REF_PREFIX.length); const resolved = doc.components?.schemas?.[name]; return resolved ?? schema; } class CompositeSchemaConverter { converters; constructor(converters) { this.converters = converters; } async convert(schema, options) { for (const converter of this.converters) { if (await converter.condition(schema, options)) { return converter.convert(schema, options); } } return [false, {}]; } } class OpenAPIGeneratorError extends Error { } class OpenAPIGenerator { serializer; converter; constructor(options = {}) { this.serializer = new StandardOpenAPIJsonSerializer(options); this.converter = new CompositeSchemaConverter(toArray(options.schemaConverters)); } /** * Generates OpenAPI specifications from oRPC routers/contracts. * * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs} */ async generate(router, options = {}) { const filter = options.filter ?? (({ contract, path }) => { return !(options.exclude?.(contract, path) ?? false); }); const doc = { ...clone(options), info: options.info ?? { title: "API Reference", version: "0.0.0" }, openapi: "3.1.1", exclude: void 0, filter: void 0, commonSchemas: void 0 }; const { baseSchemaConvertOptions, undefinedErrorJsonSchema } = await this.#resolveCommonSchemas(doc, options.commonSchemas); const contracts = []; await resolveContractProcedures({ path: [], router }, (traverseOptions) => { if (!value(filter, traverseOptions)) { return; } contracts.push(traverseOptions); }); const errors = []; for (const { contract, path } of contracts) { const stringPath = path.join("."); try { const def = contract["~orpc"]; const method = toOpenAPIMethod(fallbackContractConfig("defaultMethod", def.route.method)); const httpPath = toOpenAPIPath(def.route.path ?? toHttpPath(path)); let operationObjectRef; if (def.route.spec !== void 0 && typeof def.route.spec !== "function") { operationObjectRef = def.route.spec; } else { operationObjectRef = { operationId: def.route.operationId ?? stringPath, summary: def.route.summary, description: def.route.description, deprecated: def.route.deprecated, tags: def.route.tags?.map((tag) => tag) }; await this.#request(doc, operationObjectRef, def, baseSchemaConvertOptions); await this.#successResponse(doc, operationObjectRef, def, baseSchemaConvertOptions); await this.#errorResponse(operationObjectRef, def, baseSchemaConvertOptions, undefinedErrorJsonSchema); } if (typeof def.route.spec === "function") { operationObjectRef = def.route.spec(operationObjectRef); } doc.paths ??= {}; doc.paths[httpPath] ??= {}; doc.paths[httpPath][method] = applyCustomOpenAPIOperation(operationObjectRef, contract); } catch (e) { if (!(e instanceof OpenAPIGeneratorError)) { throw e; } errors.push( `[OpenAPIGenerator] Error occurred while generating OpenAPI for procedure at path: ${stringPath} ${e.message}` ); } } if (errors.length) { throw new OpenAPIGeneratorError( `Some error occurred during OpenAPI generation: ${errors.join("\n\n")}` ); } return this.serializer.serialize(doc)[0]; } async #resolveCommonSchemas(doc, commonSchemas) { let undefinedErrorJsonSchema = { type: "object", properties: { defined: { const: false }, code: { type: "string" }, status: { type: "number" }, message: { type: "string" }, data: {} }, required: ["defined", "code", "status", "message"] }; const baseSchemaConvertOptions = {}; if (commonSchemas) { baseSchemaConvertOptions.components = []; for (const key in commonSchemas) { const options = commonSchemas[key]; if (options.schema === void 0) { continue; } const { schema, strategy = "input" } = options; const [required, json] = await this.converter.convert(schema, { strategy }); const allowedStrategies = [strategy]; if (strategy === "input") { const [outputRequired, outputJson] = await this.converter.convert(schema, { strategy: "output" }); if (outputRequired === required && stringifyJSON(outputJson) === stringifyJSON(json)) { allowedStrategies.push("output"); } } else if (strategy === "output") { const [inputRequired, inputJson] = await this.converter.convert(schema, { strategy: "input" }); if (inputRequired === required && stringifyJSON(inputJson) === stringifyJSON(json)) { allowedStrategies.push("input"); } } baseSchemaConvertOptions.components.push({ schema, required, ref: `#/components/schemas/${key}`, allowedStrategies }); } doc.components ??= {}; doc.components.schemas ??= {}; for (const key in commonSchemas) { const options = commonSchemas[key]; if (options.schema === void 0) { if (options.error === "UndefinedError") { doc.components.schemas[key] = toOpenAPISchema(undefinedErrorJsonSchema); undefinedErrorJsonSchema = { $ref: `#/components/schemas/${key}` }; } continue; } const { schema, strategy = "input" } = options; const [, json] = await this.converter.convert( schema, { ...baseSchemaConvertOptions, strategy, minStructureDepthForRef: 1 // not allow use $ref for root schemas } ); doc.components.schemas[key] = toOpenAPISchema(json); } } return { baseSchemaConvertOptions, undefinedErrorJsonSchema }; } async #request(doc, ref, def, baseSchemaConvertOptions) { const method = fallbackContractConfig("defaultMethod", def.route.method); const details = getEventIteratorSchemaDetails(def.inputSchema); if (details) { ref.requestBody = { required: true, content: toOpenAPIEventIteratorContent( await this.converter.convert(details.yields, { ...baseSchemaConvertOptions, strategy: "input" }), await this.converter.convert(details.returns, { ...baseSchemaConvertOptions, strategy: "input" }) ) }; return; } const dynamicParams = getDynamicParams(def.route.path)?.map((v) => v.name); const inputStructure = fallbackContractConfig("defaultInputStructure", def.route.inputStructure); let [required, schema] = await this.converter.convert( def.inputSchema, { ...baseSchemaConvertOptions, strategy: "input", minStructureDepthForRef: dynamicParams?.length || inputStructure === "detailed" ? 1 : 0 } ); if (isAnySchema(schema) && !dynamicParams?.length) { return; } if (inputStructure === "compact") { if (dynamicParams?.length) { const error2 = new OpenAPIGeneratorError( 'When input structure is "compact", and path has dynamic params, input schema must be an object with all dynamic params as required.' ); if (!isObjectSchema(schema)) { throw error2; } const [paramsSchema, rest] = separateObjectSchema(schema, dynamicParams); schema = rest; required = rest.required ? rest.required.length !== 0 : false; if (!checkParamsSchema(paramsSchema, dynamicParams)) { throw error2; } ref.parameters ??= []; ref.parameters.push(...toOpenAPIParameters(paramsSchema, "path")); } if (method === "GET") { const resolvedSchema = resolveOpenAPIJsonSchemaRef(doc, schema); if (!isObjectSchema(resolvedSchema)) { throw new OpenAPIGeneratorError( 'When method is "GET", input schema must satisfy: object | any | unknown' ); } ref.parameters ??= []; ref.parameters.push(...toOpenAPIParameters(resolvedSchema, "query")); } else { ref.requestBody = { required, content: toOpenAPIContent(schema) }; } return; } const error = new OpenAPIGeneratorError( 'When input structure is "detailed", input schema must satisfy: { params?: Record<string, unknown>, query?: Record<string, unknown>, headers?: Record<string, unknown>, body?: unknown }' ); if (!isObjectSchema(schema)) { throw error; } const resolvedParamSchema = schema.properties?.params !== void 0 ? resolveOpenAPIJsonSchemaRef(doc, schema.properties.params) : void 0; if (dynamicParams?.length && (resolvedParamSchema === void 0 || !isObjectSchema(resolvedParamSchema) || !checkParamsSchema(resolvedParamSchema, dynamicParams))) { throw new OpenAPIGeneratorError( 'When input structure is "detailed" and path has dynamic params, the "params" schema must be an object with all dynamic params as required.' ); } for (const from of ["params", "query", "headers"]) { const fromSchema = schema.properties?.[from]; if (fromSchema !== void 0) { const resolvedSchema = resolveOpenAPIJsonSchemaRef(doc, fromSchema); if (!isObjectSchema(resolvedSchema)) { throw error; } const parameterIn = from === "params" ? "path" : from === "headers" ? "header" : "query"; ref.parameters ??= []; ref.parameters.push(...toOpenAPIParameters(resolvedSchema, parameterIn)); } } if (schema.properties?.body !== void 0) { ref.requestBody = { required: schema.required?.includes("body"), content: toOpenAPIContent(schema.properties.body) }; } } async #successResponse(doc, ref, def, baseSchemaConvertOptions) { const outputSchema = def.outputSchema; const status = fallbackContractConfig("defaultSuccessStatus", def.route.successStatus); const description = fallbackContractConfig("defaultSuccessDescription", def.route?.successDescription); const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(outputSchema); const outputStructure = fallbackContractConfig("defaultOutputStructure", def.route.outputStructure); if (eventIteratorSchemaDetails) { ref.responses ??= {}; ref.responses[status] = { description, content: toOpenAPIEventIteratorContent( await this.converter.convert(eventIteratorSchemaDetails.yields, { ...baseSchemaConvertOptions, strategy: "output" }), await this.converter.convert(eventIteratorSchemaDetails.returns, { ...baseSchemaConvertOptions, strategy: "output" }) ) }; return; } const [required, json] = await this.converter.convert( outputSchema, { ...baseSchemaConvertOptions, strategy: "output", minStructureDepthForRef: outputStructure === "detailed" ? 1 : 0 } ); if (outputStructure === "compact") { ref.responses ??= {}; ref.responses[status] = { description }; ref.responses[status].content = toOpenAPIContent(applySchemaOptionality(required, json)); return; } const handledStatuses = /* @__PURE__ */ new Set(); for (const item of expandUnionSchema(json)) { const error = new OpenAPIGeneratorError(` When output structure is "detailed", output schema must satisfy: { status?: number, // must be a literal number and in the range of 200-399 headers?: Record<string, unknown>, body?: unknown } But got: ${stringifyJSON(item)} `); if (!isObjectSchema(item)) { throw error; } let schemaStatus; let schemaDescription; if (item.properties?.status !== void 0) { const statusSchema = resolveOpenAPIJsonSchemaRef(doc, item.properties.status); if (typeof statusSchema !== "object" || statusSchema.const === void 0 || typeof statusSchema.const !== "number" || !Number.isInteger(statusSchema.const) || isORPCErrorStatus(statusSchema.const)) { throw error; } schemaStatus = statusSchema.const; schemaDescription = statusSchema.description; } const itemStatus = schemaStatus ?? status; const itemDescription = schemaDescription ?? description; if (handledStatuses.has(itemStatus)) { throw new OpenAPIGeneratorError(` When output structure is "detailed", each success status must be unique. But got status: ${itemStatus} used more than once. `); } handledStatuses.add(itemStatus); ref.responses ??= {}; ref.responses[itemStatus] = { description: itemDescription }; if (item.properties?.headers !== void 0) { const headersSchema = resolveOpenAPIJsonSchemaRef(doc, item.properties.headers); if (!isObjectSchema(headersSchema)) { throw error; } for (const key in headersSchema.properties) { const headerSchema = headersSchema.properties[key]; if (headerSchema !== void 0) { ref.responses[itemStatus].headers ??= {}; ref.responses[itemStatus].headers[key] = { schema: toOpenAPISchema(headerSchema), required: item.required?.includes("headers") && headersSchema.required?.includes(key) }; } } } if (item.properties?.body !== void 0) { ref.responses[itemStatus].content = toOpenAPIContent( applySchemaOptionality(item.required?.includes("body") ?? false, item.properties.body) ); } } } async #errorResponse(ref, def, baseSchemaConvertOptions, undefinedErrorSchema) { const errorMap = def.errorMap; const errors = {}; for (const code in errorMap) { const config = errorMap[code]; if (!config) { continue; } const status = fallbackORPCErrorStatus(code, config.status); const message = fallbackORPCErrorMessage(code, config.message); const [dataRequired, dataSchema] = await this.converter.convert(config.data, { ...baseSchemaConvertOptions, strategy: "output" }); errors[status] ??= []; errors[status].push({ type: "object", properties: { defined: { const: true }, code: { const: code }, status: { const: status }, message: { type: "string", default: message }, data: dataSchema }, required: dataRequired ? ["defined", "code", "status", "message", "data"] : ["defined", "code", "status", "message"] }); } ref.responses ??= {}; for (const status in errors) { const schemas = errors[status]; ref.responses[status] = { description: status, content: toOpenAPIContent({ oneOf: [ ...schemas, undefinedErrorSchema ] }) }; } } } export { CompositeSchemaConverter as C, LOGIC_KEYWORDS as L, OpenAPIGenerator as O, applyCustomOpenAPIOperation as a, toOpenAPIMethod as b, customOpenAPIOperation as c, toOpenAPIContent as d, toOpenAPIEventIteratorContent as e, toOpenAPIParameters as f, getCustomOpenAPIOperation as g, checkParamsSchema as h, toOpenAPISchema as i, isFileSchema as j, isObjectSchema as k, isAnySchema as l, filterSchemaBranches as m, applySchemaOptionality as n, expandUnionSchema as o, expandArrayableSchema as p, isPrimitiveSchema as q, resolveOpenAPIJsonSchemaRef as r, separateObjectSchema as s, toOpenAPIPath as t };