@orpc/openapi 2.0.0-beta.47 → 2.0.0-beta.49

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.
Files changed (93) hide show
  1. package/README.md +6 -7
  2. package/dist/adapters/aws-lambda/index.d.ts +10 -22
  3. package/dist/adapters/aws-lambda/index.js +1 -0
  4. package/dist/adapters/aws-lambda/openapi-handler.d.ts +18 -0
  5. package/dist/adapters/aws-lambda/openapi-handler.js +18 -0
  6. package/dist/adapters/fastify/index.d.ts +1 -23
  7. package/dist/adapters/fastify/index.js +1 -0
  8. package/dist/adapters/fastify/openapi-handler.d.ts +15 -0
  9. package/dist/adapters/fastify/openapi-handler.js +15 -0
  10. package/dist/adapters/fetch/index.d.ts +2 -37
  11. package/dist/adapters/fetch/index.js +2 -0
  12. package/dist/adapters/fetch/openapi-handler.d.ts +15 -0
  13. package/dist/adapters/fetch/openapi-handler.js +15 -0
  14. package/dist/adapters/fetch/openapi-link.d.ts +21 -0
  15. package/dist/adapters/fetch/openapi-link.js +20 -0
  16. package/dist/adapters/node/index.d.ts +1 -23
  17. package/dist/adapters/node/index.js +1 -0
  18. package/dist/adapters/node/openapi-handler.d.ts +15 -0
  19. package/dist/adapters/node/openapi-handler.js +15 -0
  20. package/dist/adapters/standard/index.d.ts +3 -56
  21. package/dist/adapters/standard/index.js +3 -0
  22. package/dist/adapters/standard/openapi-handler-codec.d.ts +62 -0
  23. package/dist/adapters/standard/openapi-handler-codec.js +220 -0
  24. package/dist/adapters/standard/{index.d.mts → openapi-link-codec.d.ts} +25 -19
  25. package/dist/adapters/standard/openapi-link-codec.js +405 -0
  26. package/dist/adapters/standard/openapi-matcher.d.ts +29 -0
  27. package/dist/adapters/standard/openapi-matcher.js +108 -0
  28. package/dist/adapters/standard/utils.d.ts +4 -0
  29. package/dist/adapters/standard/utils.js +47 -0
  30. package/dist/bracket-notation.d.ts +26 -0
  31. package/dist/bracket-notation.js +185 -0
  32. package/dist/client-factory.d.ts +24 -0
  33. package/dist/client-factory.js +13 -0
  34. package/dist/constants.d.ts +4 -0
  35. package/dist/constants.js +4 -0
  36. package/dist/extensions/route.d.ts +3 -7
  37. package/dist/extensions/route.js +12 -0
  38. package/dist/helpers/{index.d.mts → form-data.d.ts} +2 -4
  39. package/dist/helpers/form-data.js +90 -0
  40. package/dist/helpers/index.d.ts +1 -59
  41. package/dist/helpers/index.js +1 -0
  42. package/dist/index.d.ts +12 -165
  43. package/dist/index.js +11 -0
  44. package/dist/{shared/openapi.zGZlCOwp.d.mts → meta.d.ts} +14 -18
  45. package/dist/meta.js +84 -0
  46. package/dist/openapi-generator-components.d.ts +31 -0
  47. package/dist/openapi-generator-components.js +275 -0
  48. package/dist/openapi-generator-operation.d.ts +34 -0
  49. package/dist/openapi-generator-operation.js +469 -0
  50. package/dist/openapi-generator.d.ts +92 -0
  51. package/dist/openapi-generator.js +147 -0
  52. package/dist/openapi-json-serializer.d.ts +79 -0
  53. package/dist/openapi-json-serializer.js +260 -0
  54. package/dist/openapi-serializer.d.ts +43 -0
  55. package/dist/openapi-serializer.js +93 -0
  56. package/dist/plugins/index.d.ts +1 -121
  57. package/dist/plugins/index.js +1 -0
  58. package/dist/plugins/{index.d.mts → openapi-reference.d.ts} +15 -21
  59. package/dist/plugins/openapi-reference.js +187 -0
  60. package/dist/router-utils.d.ts +20 -0
  61. package/dist/router-utils.js +36 -0
  62. package/dist/types.d.ts +31 -0
  63. package/dist/types.js +1 -0
  64. package/dist/utils.d.ts +14 -0
  65. package/dist/utils.js +47 -0
  66. package/package.json +69 -71
  67. package/dist/adapters/aws-lambda/index.d.mts +0 -27
  68. package/dist/adapters/aws-lambda/index.mjs +0 -21
  69. package/dist/adapters/fastify/index.d.mts +0 -23
  70. package/dist/adapters/fastify/index.mjs +0 -21
  71. package/dist/adapters/fetch/index.d.mts +0 -37
  72. package/dist/adapters/fetch/index.mjs +0 -34
  73. package/dist/adapters/node/index.d.mts +0 -23
  74. package/dist/adapters/node/index.mjs +0 -21
  75. package/dist/adapters/standard/index.mjs +0 -12
  76. package/dist/extensions/route.d.mts +0 -41
  77. package/dist/extensions/route.mjs +0 -14
  78. package/dist/helpers/index.mjs +0 -39
  79. package/dist/index.d.mts +0 -166
  80. package/dist/index.mjs +0 -780
  81. package/dist/plugins/index.mjs +0 -167
  82. package/dist/shared/openapi.B9PQzqBn.mjs +0 -49
  83. package/dist/shared/openapi.CQkXu1nY.mjs +0 -366
  84. package/dist/shared/openapi.Covi8zVE.d.mts +0 -33
  85. package/dist/shared/openapi.Covi8zVE.d.ts +0 -33
  86. package/dist/shared/openapi.DfmCR1pB.d.mts +0 -94
  87. package/dist/shared/openapi.DtEVcxuW.mjs +0 -149
  88. package/dist/shared/openapi.E3ZBiweM.mjs +0 -353
  89. package/dist/shared/openapi.Y4K_-I5W.d.ts +0 -94
  90. package/dist/shared/openapi.YMRD3b4R.d.mts +0 -157
  91. package/dist/shared/openapi.YMRD3b4R.d.ts +0 -157
  92. package/dist/shared/openapi.g7ucL05o.mjs +0 -410
  93. package/dist/shared/openapi.zGZlCOwp.d.ts +0 -329
@@ -0,0 +1,469 @@
1
+ import { getAsyncIteratorObjectSchemasDetails } from '@orpc/contract';
2
+ import { combineJsonObjectSchemaEntries, combineJsonSchemasWithComposition, containsJsonFileSchema, extractJsonObjectSchemaAdditionalProperties, extractJsonObjectSchemaEntries, flattenJsonUnionSchema, isJsonFileSchema, isJsonPrimitiveSchema, isUnconstrainedSchema, matchArrayableJsonSchema, resolveJsonSchemaRootLocalRef, } from '@orpc/json-schema';
3
+ import { DEFAULT_ERROR_STATUS, DEFAULT_SUCCESS_STATUS } from '@orpc/server';
4
+ import { getOwn, stringifyJSON, value } from '@orpc/shared';
5
+ import { DEFAULT_OPENAPI_INPUT_STRUCTURE, DEFAULT_OPENAPI_METHOD, DEFAULT_OPENAPI_OUTPUT_STRUCTURE, DEFAULT_OPENAPI_SUCCESS_DESCRIPTION, } from './constants.js';
6
+ import { isBodylessMethod } from './utils.js';
7
+ export class OpenAPIGeneratorError extends TypeError {
8
+ }
9
+ export function toOpenAPIPath(path, dynamicPathParams) {
10
+ if (!dynamicPathParams?.length) {
11
+ return path;
12
+ }
13
+ let normalized = '';
14
+ let currentIndex = 0;
15
+ for (const param of dynamicPathParams) {
16
+ normalized += path.slice(currentIndex, param.startIndex);
17
+ normalized += `{${param.parameterName}}`;
18
+ currentIndex = param.startIndex + param.segment.length;
19
+ }
20
+ normalized += path.slice(currentIndex);
21
+ return normalized;
22
+ }
23
+ export function buildRequest(ctx, operation, def, meta, dynamicPathParams) {
24
+ const method = meta?.method ?? DEFAULT_OPENAPI_METHOD;
25
+ const inputStructure = meta?.inputStructure ?? DEFAULT_OPENAPI_INPUT_STRUCTURE;
26
+ const dynamicParams = dynamicPathParams?.map((v) => v.parameterName);
27
+ if (inputStructure === 'compact') {
28
+ const iteratorDetails = getAsyncIteratorObjectSchemasDetails(def.inputSchemas);
29
+ if (iteratorDetails) {
30
+ renderPathParameters(ctx, operation, dynamicParams, undefined, undefined);
31
+ operation.requestBody = {
32
+ required: true,
33
+ content: toAsyncIteratorObjectContent(ctx, 'input', ctx.convertSchemas(iteratorDetails.yieldSchemas, 'input'), ctx.convertSchemas(iteratorDetails.returnSchemas, 'input')),
34
+ };
35
+ return;
36
+ }
37
+ }
38
+ const [schema, optional] = ctx.convertSchemas(def.inputSchemas, 'input');
39
+ if (isUnconstrainedSchema(schema) && !dynamicParams?.length) {
40
+ return;
41
+ }
42
+ const parts = inputStructure === 'compact'
43
+ ? extractCompactRequestParts(schema, optional, method, dynamicParams)
44
+ : extractDetailedRequestParts(schema);
45
+ renderPathParameters(ctx, operation, dynamicParams, parts.paramsEntries, meta?.paramsStyles);
46
+ renderQueryParameters(ctx, operation, parts.queryEntries, meta?.queryStyles);
47
+ renderHeaderParameters(ctx, operation, parts.headersEntries);
48
+ if (parts.bodySchema !== undefined) {
49
+ operation.requestBody = {
50
+ required: parts.bodyOptional ? undefined : true,
51
+ content: toBodyContent(ctx, 'input', parts.bodySchema),
52
+ };
53
+ }
54
+ }
55
+ function extractCompactRequestParts(schema, optional, method, dynamicParams) {
56
+ const entries = extractJsonObjectSchemaEntries(schema);
57
+ if (!entries && isBodylessMethod(method)) {
58
+ throw new OpenAPIGeneratorError(`method is ${method} but the input schema is not an object.\n` +
59
+ ` ${method} sends every input field as a query parameter, so the input must be an object schema.\n` +
60
+ ` Fix: make the input an object, or use a method with a request body (POST, PUT, PATCH, DELETE).`);
61
+ }
62
+ const paramsEntries = entries?.filter(([name]) => dynamicParams?.includes(name));
63
+ const restEntries = entries?.filter(([name]) => !dynamicParams?.includes(name));
64
+ const hasBody = !isBodylessMethod(method);
65
+ const bodySchema = !hasBody
66
+ ? undefined
67
+ : !dynamicParams?.length
68
+ ? schema
69
+ : restEntries
70
+ ? combineJsonObjectSchemaEntries(restEntries, extractJsonObjectSchemaAdditionalProperties(schema))
71
+ : undefined;
72
+ return {
73
+ paramsEntries,
74
+ queryEntries: isBodylessMethod(method) ? restEntries : undefined,
75
+ headersEntries: undefined,
76
+ bodySchema,
77
+ bodyOptional: !dynamicParams?.length
78
+ ? optional
79
+ : restEntries?.every(([, , optional]) => optional),
80
+ };
81
+ }
82
+ function extractDetailedRequestParts(schema) {
83
+ const entries = extractJsonObjectSchemaEntries(schema);
84
+ if (!entries) {
85
+ throw new OpenAPIGeneratorError(`inputStructure is "detailed" but the input schema is not an object.\n` +
86
+ ` Expected an object shaped like: { params?: object, query?: object, headers?: object, body?: unknown }`);
87
+ }
88
+ const section = (name) => entries.find(([entryName]) => entryName === name);
89
+ return {
90
+ paramsEntries: extractJsonObjectSchemaEntries(section('params')?.[1] ?? false),
91
+ queryEntries: extractJsonObjectSchemaEntries(section('query')?.[1] ?? false),
92
+ headersEntries: extractJsonObjectSchemaEntries(section('headers')?.[1] ?? false),
93
+ bodySchema: section('body')?.[1],
94
+ bodyOptional: section('body')?.[2],
95
+ };
96
+ }
97
+ function renderPathParameters(ctx, operation, dynamicParams, paramsEntries, paramsStyles) {
98
+ if (!dynamicParams?.length) {
99
+ return;
100
+ }
101
+ if (!paramsEntries) {
102
+ throw new OpenAPIGeneratorError(`the route declares path params (${dynamicParams.map((p) => `{${p}}`).join(', ')}) but there is no object schema to source them from.\n` +
103
+ ` compact mode: the input schema must be an object containing each param.\n` +
104
+ ` detailed mode: the input's "params" section must be an object containing each param.`);
105
+ }
106
+ for (const name of dynamicParams) {
107
+ const entry = paramsEntries.find(([entryName]) => entryName === name);
108
+ if (!entry) {
109
+ throw new OpenAPIGeneratorError(`dynamic param "{${name}}" is missing from the input schema.\n` +
110
+ ` Route params: ${dynamicParams.map((p) => `{${p}}`).join(', ')}\n` +
111
+ ` Schema keys: ${paramsEntries.map(([n]) => n).join(', ') || '(none)'}`);
112
+ }
113
+ if (entry[2]) {
114
+ throw new OpenAPIGeneratorError(`dynamic param "${name}" is optional in the input schema.\n` +
115
+ ` OpenAPI requires path params to be required. Make "${name}" required.`);
116
+ }
117
+ const style = paramsStyles?.[name];
118
+ const parameter = {
119
+ in: 'path',
120
+ required: true,
121
+ name,
122
+ schema: ctx.registry.toOpenAPISchema(entry[1], 'input'),
123
+ };
124
+ if (style === 'comma-delimited-array' || style === 'comma-delimited-object') {
125
+ parameter.style = 'simple';
126
+ parameter.explode = false;
127
+ }
128
+ else {
129
+ const _expect = style;
130
+ }
131
+ operation.parameters ??= [];
132
+ operation.parameters.push(parameter);
133
+ }
134
+ }
135
+ function renderQueryParameters(ctx, operation, queryEntries, queryStyles) {
136
+ for (const [name, schema, optional] of queryEntries ?? []) {
137
+ const style = queryStyles?.[name];
138
+ const parameter = {
139
+ in: 'query',
140
+ name,
141
+ schema: ctx.registry.toOpenAPISchema(schema, 'input'),
142
+ allowEmptyValue: true,
143
+ allowReserved: true,
144
+ };
145
+ if (!optional) {
146
+ parameter.required = true;
147
+ }
148
+ if (style === 'comma-delimited-array' || style === 'comma-delimited-object') {
149
+ parameter.explode = false;
150
+ }
151
+ else if (style === 'pipe-delimited-array' || style === 'pipe-delimited-object') {
152
+ parameter.style = 'pipeDelimited';
153
+ }
154
+ else if (style === 'space-delimited-array' || style === 'space-delimited-object') {
155
+ parameter.style = 'spaceDelimited';
156
+ }
157
+ else if (style === 'json') {
158
+ parameter.content = {
159
+ 'application/json': { schema: parameter.schema },
160
+ };
161
+ delete parameter.schema;
162
+ delete parameter.allowReserved;
163
+ }
164
+ else if (style === undefined) {
165
+ if (!flattenJsonUnionSchema(schema).every(isPrimitive)) {
166
+ const arrayable = matchArrayableJsonSchema(schema);
167
+ if (!arrayable || !flattenJsonUnionSchema(arrayable[0]).every(isPrimitive)) {
168
+ parameter.style = 'deepObject';
169
+ parameter.explode = true;
170
+ }
171
+ }
172
+ }
173
+ else {
174
+ const _expect = style;
175
+ }
176
+ operation.parameters ??= [];
177
+ operation.parameters.push(parameter);
178
+ }
179
+ }
180
+ function renderHeaderParameters(ctx, operation, headersEntries) {
181
+ for (const [name, schema, optional] of headersEntries ?? []) {
182
+ operation.parameters ??= [];
183
+ operation.parameters.push({
184
+ in: 'header',
185
+ name,
186
+ required: optional ? undefined : true,
187
+ schema: ctx.registry.toOpenAPISchema(schema, 'input'),
188
+ });
189
+ }
190
+ }
191
+ export function buildSuccessResponse(ctx, operation, def, meta) {
192
+ const status = meta?.successStatus ?? DEFAULT_SUCCESS_STATUS;
193
+ const description = meta?.successDescription ?? DEFAULT_OPENAPI_SUCCESS_DESCRIPTION;
194
+ const outputStructure = meta?.outputStructure ?? DEFAULT_OPENAPI_OUTPUT_STRUCTURE;
195
+ if (outputStructure === 'compact') {
196
+ const iteratorDetails = getAsyncIteratorObjectSchemasDetails(def.outputSchemas);
197
+ if (iteratorDetails) {
198
+ operation.responses ??= {};
199
+ operation.responses[toResponseStatusKey(status)] = {
200
+ description,
201
+ content: toAsyncIteratorObjectContent(ctx, 'output', ctx.convertSchemas(iteratorDetails.yieldSchemas, 'output'), ctx.convertSchemas(iteratorDetails.returnSchemas, 'output')),
202
+ };
203
+ return;
204
+ }
205
+ }
206
+ const [schema] = ctx.convertSchemas(def.outputSchemas, 'output');
207
+ if (isUnconstrainedSchema(schema) || outputStructure === 'compact') {
208
+ operation.responses ??= {};
209
+ operation.responses[toResponseStatusKey(status)] = {
210
+ description,
211
+ content: toBodyContent(ctx, 'output', schema),
212
+ };
213
+ return;
214
+ }
215
+ for (const [responseStatus, parts] of extractDetailedResponseParts(schema, status)) {
216
+ const responseObject = {
217
+ description: parts.descriptions.length ? parts.descriptions.join(', ') : description,
218
+ };
219
+ if (parts.bodies.length) {
220
+ responseObject.content = toBodyContent(ctx, 'output', combineJsonSchemasWithComposition('anyOf', parts.bodies));
221
+ }
222
+ if (parts.headers.length) {
223
+ const entries = extractJsonObjectSchemaEntries(combineJsonSchemasWithComposition('anyOf', parts.headers));
224
+ entries?.forEach(([name, schema, optional]) => {
225
+ responseObject.headers ??= {};
226
+ responseObject.headers[name] = {
227
+ required: optional ? undefined : true,
228
+ schema: ctx.registry.toOpenAPISchema(schema, 'output'),
229
+ };
230
+ });
231
+ }
232
+ operation.responses ??= {};
233
+ operation.responses[toResponseStatusKey(responseStatus)] = responseObject;
234
+ }
235
+ }
236
+ /**
237
+ * Formats a numeric HTTP status as a Responses Object key.
238
+ */
239
+ function toResponseStatusKey(status) {
240
+ return String(status);
241
+ }
242
+ /**
243
+ * Flattens a detailed output schema (a union of `{ status?, headers?, body? }` objects)
244
+ * into per-status response pieces.
245
+ */
246
+ function extractDetailedResponseParts(schema, defaultStatus) {
247
+ const partsByStatus = new Map();
248
+ for (const item of flattenJsonUnionSchema(schema)) {
249
+ const entries = extractJsonObjectSchemaEntries(item);
250
+ if (!entries) {
251
+ throw new OpenAPIGeneratorError(`outputStructure is "detailed" but the output schema (or one of its union members) is not an object.\n` +
252
+ ` Expected each member shaped like: { status?: number (< 400), headers?: object, body?: unknown }`);
253
+ }
254
+ const [, statusSchema, statusOptional = true] = entries.find(([name]) => name === 'status') ?? [];
255
+ const statuses = statusSchema === undefined
256
+ ? new Map()
257
+ : extractDetailedStatuses(statusSchema);
258
+ if (!statuses) {
259
+ throw new OpenAPIGeneratorError(`invalid "status" field in the detailed output schema.\n` +
260
+ ` Expected: literal integers below 400 (const, enum, or a union of them)\n` +
261
+ ` Received: ${stringifyJSON(statusSchema)}`);
262
+ }
263
+ // an omitted status falls back to the success status at runtime
264
+ if (statusOptional && !statuses.has(defaultStatus)) {
265
+ statuses.set(defaultStatus, undefined);
266
+ }
267
+ const headersSchema = entries.find(([name]) => name === 'headers')?.[1];
268
+ const bodySchema = entries.find(([name]) => name === 'body')?.[1];
269
+ for (const [status, description] of statuses) {
270
+ let parts = partsByStatus.get(status);
271
+ if (!parts) {
272
+ parts = { descriptions: [], bodies: [], headers: [] };
273
+ partsByStatus.set(status, parts);
274
+ }
275
+ if (description !== undefined) {
276
+ parts.descriptions.push(description);
277
+ }
278
+ if (headersSchema !== undefined) {
279
+ parts.headers.push(headersSchema);
280
+ }
281
+ if (bodySchema !== undefined) {
282
+ parts.bodies.push(bodySchema);
283
+ }
284
+ }
285
+ }
286
+ return partsByStatus;
287
+ }
288
+ /**
289
+ * Collects every status a detailed output `status` schema allows, mapped to its description.
290
+ * Accepts `const`, `enum` (how Effect, arktype, and valibot `picklist` emit literals), or a union of them.
291
+ * Returns `undefined` when any member is not a literal integer below 400.
292
+ */
293
+ function extractDetailedStatuses(schema) {
294
+ const statuses = new Map();
295
+ for (const member of flattenJsonUnionSchema(schema)) {
296
+ if (typeof member !== 'object') {
297
+ return undefined;
298
+ }
299
+ const values = member.const !== undefined ? [member.const] : member.enum;
300
+ if (!values?.length) {
301
+ return undefined;
302
+ }
303
+ for (const value of values) {
304
+ if (!Number.isInteger(value) || value >= 400) {
305
+ return undefined;
306
+ }
307
+ if (!statuses.has(value)) {
308
+ statuses.set(value, member.description);
309
+ }
310
+ }
311
+ }
312
+ return statuses.size ? statuses : undefined;
313
+ }
314
+ export function buildErrorResponse(ctx, operation, def) {
315
+ const definitionsByStatus = new Map();
316
+ for (const code of Object.keys(def.errorMap)) {
317
+ const config = def.errorMap[code];
318
+ if (!config) {
319
+ continue;
320
+ }
321
+ const status = getOwn(ctx.errorStatusMap, code) ?? DEFAULT_ERROR_STATUS;
322
+ const [dataJsonSchema, dataOptional] = ctx.convertSchemas(config.data !== undefined ? [config.data] : undefined, 'output');
323
+ let definitions = definitionsByStatus.get(status);
324
+ if (!definitions) {
325
+ definitions = [];
326
+ definitionsByStatus.set(status, definitions);
327
+ }
328
+ definitions.push({ code, dataJsonSchema, dataOptional, defaultMessage: config.message });
329
+ }
330
+ if (!definitionsByStatus.size) {
331
+ return;
332
+ }
333
+ const undefinedErrorSchema = ctx.registry.register('UndefinedError', {
334
+ title: 'UndefinedError',
335
+ type: 'object',
336
+ properties: {
337
+ defined: { const: false },
338
+ code: { type: 'string' },
339
+ message: { type: 'string' },
340
+ data: {},
341
+ },
342
+ required: ['defined', 'code', 'message'],
343
+ });
344
+ for (const [status, definitions] of definitionsByStatus.entries()) {
345
+ const descriptions = definitions
346
+ .map(({ defaultMessage }) => defaultMessage)
347
+ .filter((m) => m !== undefined);
348
+ const definedErrors = definitions.map((def) => ({
349
+ ...def,
350
+ dataJsonSchema: ctx.registry.hoistDefs(def.dataJsonSchema, 'output'),
351
+ }));
352
+ // lazy, so per-code error components are only registered when the default schema is actually used
353
+ const defaultSchema = () => combineJsonSchemasWithComposition('oneOf', [
354
+ ...definedErrors.map(({ code, dataJsonSchema, dataOptional }) => {
355
+ return ctx.registry.register(toErrorComponentName(code), {
356
+ title: code,
357
+ ...combineJsonObjectSchemaEntries([
358
+ ['defined', { const: true }, false],
359
+ ['code', { const: code }, false],
360
+ // avoid using the defaultMessage here to improve component reusability
361
+ ['message', { type: 'string' }, false],
362
+ ['data', dataJsonSchema, dataOptional],
363
+ ]),
364
+ });
365
+ }),
366
+ undefinedErrorSchema,
367
+ ]);
368
+ const responseSchema = ctx.errorResponseBodySchema === undefined
369
+ ? defaultSchema()
370
+ : value(ctx.errorResponseBodySchema, definedErrors, status, defaultSchema);
371
+ const responseObject = {
372
+ description: descriptions.length ? descriptions.join(', ') : status.toString(),
373
+ };
374
+ if (responseSchema !== undefined && responseSchema !== null) {
375
+ responseObject.content = {
376
+ [ctx.errorResponseContentType]: {
377
+ schema: ctx.registry.toOpenAPISchema(responseSchema, 'output'),
378
+ },
379
+ };
380
+ }
381
+ operation.responses ??= {};
382
+ operation.responses[toResponseStatusKey(status)] = responseObject;
383
+ }
384
+ }
385
+ /**
386
+ * Converts an error code into a component name, e.g. `BAD_REQUEST` -> `BadRequest`.
387
+ */
388
+ function toErrorComponentName(code) {
389
+ const name = code
390
+ .split(/[^a-z0-9]+/i)
391
+ .filter(Boolean)
392
+ .map((part) => {
393
+ const rest = part.slice(1);
394
+ return (part.charAt(0).toUpperCase() + (rest === rest.toUpperCase() ? rest.toLowerCase() : rest));
395
+ })
396
+ .join('');
397
+ return name || 'Error';
398
+ }
399
+ function toAsyncIteratorObjectContent(ctx, direction, [yieldSchema, yieldOptional], [returnSchema, returnOptional]) {
400
+ const schema = combineJsonSchemasWithComposition('oneOf', [
401
+ combineJsonObjectSchemaEntries([
402
+ ['event', { const: 'message' }, false],
403
+ ['data', yieldSchema, yieldOptional],
404
+ ['id', { type: 'string' }, true],
405
+ ['retry', { type: 'number' }, true],
406
+ ]),
407
+ combineJsonObjectSchemaEntries([
408
+ ['event', { const: 'close' }, false],
409
+ ['data', returnSchema, returnOptional],
410
+ ['id', { type: 'string' }, true],
411
+ ['retry', { type: 'number' }, true],
412
+ ]),
413
+ {
414
+ type: 'object',
415
+ properties: {
416
+ event: { const: 'error' },
417
+ data: {},
418
+ id: { type: 'string' },
419
+ retry: { type: 'number' },
420
+ },
421
+ required: ['event'],
422
+ },
423
+ ]);
424
+ return {
425
+ 'text/event-stream': {
426
+ schema: ctx.registry.toOpenAPISchema(schema, direction),
427
+ },
428
+ };
429
+ }
430
+ function toBodyContent(ctx, direction, schema) {
431
+ const fileSchemasByMediaType = new Map();
432
+ const rest = flattenJsonUnionSchema(schema).filter((s) => {
433
+ const resolved = resolveJsonSchemaRootLocalRef(s);
434
+ if (!isJsonFileSchema(resolved)) {
435
+ return !isUnconstrainedSchema(s);
436
+ }
437
+ const contentMediaType = resolved.contentMediaType ?? '*/*';
438
+ const schemas = fileSchemasByMediaType.get(contentMediaType);
439
+ if (schemas) {
440
+ schemas.push(s);
441
+ }
442
+ else {
443
+ fileSchemasByMediaType.set(contentMediaType, [s]);
444
+ }
445
+ return false;
446
+ });
447
+ const content = {};
448
+ if (rest.length > 0) {
449
+ const restSchema = fileSchemasByMediaType.size
450
+ ? combineJsonSchemasWithComposition('anyOf', rest)
451
+ : schema;
452
+ const hasNestedFiles = containsJsonFileSchema(restSchema);
453
+ const contentType = hasNestedFiles ? 'multipart/form-data' : 'application/json';
454
+ const fileSchemas = fileSchemasByMediaType.get(contentType);
455
+ fileSchemasByMediaType.delete(contentType);
456
+ content[contentType] = {
457
+ schema: ctx.registry.toOpenAPISchema(combineJsonSchemasWithComposition('anyOf', [restSchema, ...(fileSchemas ?? [])]), direction),
458
+ };
459
+ }
460
+ for (const [contentType, schemas] of fileSchemasByMediaType.entries()) {
461
+ content[contentType] = {
462
+ schema: ctx.registry.toOpenAPISchema(combineJsonSchemasWithComposition('anyOf', schemas), direction),
463
+ };
464
+ }
465
+ return content;
466
+ }
467
+ function isPrimitive(schema) {
468
+ return isJsonPrimitiveSchema(resolveJsonSchemaRootLocalRef(schema));
469
+ }
@@ -0,0 +1,92 @@
1
+ import type { AnyProcedureContract, RouterContract } from '@orpc/contract';
2
+ import type { JsonSchema, JsonSchemaConverter } from '@orpc/json-schema';
3
+ import type { AnyProcedure, AnyRouter } from '@orpc/server';
4
+ import type { Public, Value } from '@orpc/shared';
5
+ import type { OpenAPIErrorBodyDefinition } from './openapi-generator-operation.ts';
6
+ import { OpenAPIJsonSerializer } from './openapi-json-serializer.ts';
7
+ import type { OpenAPIDocument, OpenAPIV3_2, OpenAPIVersion } from './types.ts';
8
+ export { OpenAPIGeneratorError } from './openapi-generator-operation.ts';
9
+ export type { OpenAPIErrorBodyDefinition } from './openapi-generator-operation.ts';
10
+ export interface OpenAPIGeneratorOptions {
11
+ converters?: JsonSchemaConverter[] | undefined;
12
+ /**
13
+ * The serializer used to serialize the generated OpenAPI documentation
14
+ */
15
+ serializer?: Public<OpenAPIJsonSerializer> | undefined;
16
+ }
17
+ export interface OpenAPIGeneratorGenerateOptions<TVersion extends OpenAPIVersion> {
18
+ /**
19
+ * The OpenAPI version of the generated document.
20
+ * The document is generated as OpenAPI 3.2 and downgraded when an older version is requested.
21
+ * The minor version selects the conversion, the document carries the exact value, such as `3.1.0`.
22
+ *
23
+ * @default '3.2.0'
24
+ */
25
+ version?: TVersion | undefined;
26
+ /**
27
+ * OpenAPI 3.2 document fields to start from, such as `info`, `servers`, or `components`.
28
+ * They are downgraded with the rest of the document when an older `version` is requested.
29
+ * The `openapi` field is derived from `version`.
30
+ */
31
+ base?: Partial<Omit<OpenAPIV3_2.OpenAPIObject, 'openapi'>> | undefined;
32
+ /**
33
+ * Root-level `$defs` are always moved into `components.schemas`.
34
+ * Use this to customize the component name of a hoisted def.
35
+ *
36
+ * @remarks
37
+ * - Characters OpenAPI does not allow in component keys (anything but `a-z`, `A-Z`, `0-9`, `.`, `_`, `-`)
38
+ * are replaced by `_` in the returned name, e.g. `User Profile` becomes `User_Profile`.
39
+ * - The returned name is a preference, conflicting names are still postfixed (`Planet`, `PlanetInput`, `Planet2`, ...).
40
+ *
41
+ * @default defName => defName
42
+ */
43
+ componentName?: ((defName: string, defSchema: JsonSchema) => string) | undefined;
44
+ /**
45
+ * Filter procedures. Return `false` to exclude a procedure from the OpenAPI specification.
46
+ *
47
+ * @default true
48
+ */
49
+ filter?: Value<boolean, [contract: AnyProcedureContract | AnyProcedure, path: string[]]> | undefined;
50
+ /**
51
+ * Define a custom JSON schema for the error response body when using
52
+ * type-safe errors. Helps align ORPC error formatting with existing API
53
+ * response standards or conventions.
54
+ *
55
+ * @remarks
56
+ * - Return `defaultSchema()` to keep the default schema, or `null | undefined` to document an empty body, matching an `errorResponseBodyEncoder` that returns `undefined`.
57
+ * - The schema is an OpenAPI 3.2 Schema Object, it is downgraded with the rest of the document when an older `version` is requested.
58
+ */
59
+ errorResponseBodySchema?: Value<JsonSchema | null | undefined, [
60
+ definedErrors: OpenAPIErrorBodyDefinition[],
61
+ status: number,
62
+ defaultSchema: () => JsonSchema
63
+ ]> | undefined;
64
+ /**
65
+ * Media type of error responses in the generated document, e.g. `application/problem+json`.
66
+ * Should match the handler's `errorResponseContentType`.
67
+ *
68
+ * @default 'application/json'
69
+ */
70
+ errorResponseContentType?: string | undefined;
71
+ /**
72
+ * Mapping ORPCError Code -> HTTP Status Code
73
+ * Codes missing from the map fall back to `DEFAULT_ERROR_STATUS` (400).
74
+ *
75
+ * @default COMMON_ERROR_STATUS_MAP
76
+ */
77
+ errorStatusMap?: Record<string, number> | undefined;
78
+ }
79
+ /**
80
+ * Generates an OpenAPI document from a contract or router.
81
+ * Relies on JSON schema converters to translate input, output, and error schemas into JSON Schemas.
82
+ *
83
+ * @see {@link https://orpc.dev/docs/openapi/specification#openapi-generator | OpenAPI Specification - OpenAPI Generator}
84
+ */
85
+ export declare class OpenAPIGenerator {
86
+ private readonly serializer;
87
+ private readonly converter;
88
+ constructor(options?: OpenAPIGeneratorOptions);
89
+ generate<TVersion extends OpenAPIVersion = '3.2.0'>(router: RouterContract | AnyRouter, options?: OpenAPIGeneratorGenerateOptions<TVersion>): Promise<OpenAPIDocument<TVersion>>;
90
+ private convertSchema;
91
+ private convertSchemas;
92
+ }