@orpc/openapi 0.0.0-next.ef3ba82 → 0.0.0-next.f107a0e

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 (35) hide show
  1. package/README.md +101 -0
  2. package/dist/adapters/aws-lambda/index.d.mts +17 -0
  3. package/dist/adapters/aws-lambda/index.d.ts +17 -0
  4. package/dist/adapters/aws-lambda/index.mjs +18 -0
  5. package/dist/adapters/fetch/index.d.mts +17 -0
  6. package/dist/adapters/fetch/index.d.ts +17 -0
  7. package/dist/adapters/fetch/index.mjs +18 -0
  8. package/dist/adapters/node/index.d.mts +17 -0
  9. package/dist/adapters/node/index.d.ts +17 -0
  10. package/dist/adapters/node/index.mjs +18 -0
  11. package/dist/adapters/standard/index.d.mts +35 -0
  12. package/dist/adapters/standard/index.d.ts +35 -0
  13. package/dist/adapters/standard/index.mjs +9 -0
  14. package/dist/index.d.mts +109 -0
  15. package/dist/index.d.ts +109 -0
  16. package/dist/index.mjs +41 -0
  17. package/dist/plugins/index.d.mts +69 -0
  18. package/dist/plugins/index.d.ts +69 -0
  19. package/dist/plugins/index.mjs +108 -0
  20. package/dist/shared/openapi.C_UtQ8Us.mjs +179 -0
  21. package/dist/shared/openapi.D3j94c9n.d.mts +12 -0
  22. package/dist/shared/openapi.D3j94c9n.d.ts +12 -0
  23. package/dist/shared/openapi.DaYgbD_w.mjs +652 -0
  24. package/dist/shared/openapi.qZLdpE0a.d.mts +52 -0
  25. package/dist/shared/openapi.qZLdpE0a.d.ts +52 -0
  26. package/package.json +35 -21
  27. package/dist/fetch.js +0 -668
  28. package/dist/index.js +0 -4421
  29. package/dist/src/fetch/base-handler.d.ts +0 -14
  30. package/dist/src/fetch/index.d.ts +0 -3
  31. package/dist/src/fetch/server-handler.d.ts +0 -2
  32. package/dist/src/fetch/serverless-handler.d.ts +0 -2
  33. package/dist/src/generator.d.ts +0 -23
  34. package/dist/src/index.d.ts +0 -2
  35. package/dist/src/zod-to-json-schema.d.ts +0 -42
@@ -0,0 +1,652 @@
1
+ import { isORPCErrorStatus, fallbackORPCErrorStatus, fallbackORPCErrorMessage } from '@orpc/client';
2
+ import { toHttpPath } from '@orpc/client/standard';
3
+ import { fallbackContractConfig, getEventIteratorSchemaDetails } from '@orpc/contract';
4
+ import { standardizeHTTPPath, StandardOpenAPIJsonSerializer, getDynamicParams } from '@orpc/openapi-client/standard';
5
+ import { isProcedure, resolveContractProcedures } from '@orpc/server';
6
+ import { isObject, stringifyJSON, findDeepMatches, toArray, clone } from '@orpc/shared';
7
+ import { TypeName } from 'json-schema-typed/draft-2020-12';
8
+
9
+ const OPERATION_EXTENDER_SYMBOL = Symbol("ORPC_OPERATION_EXTENDER");
10
+ function customOpenAPIOperation(o, extend) {
11
+ return new Proxy(o, {
12
+ get(target, prop, receiver) {
13
+ if (prop === OPERATION_EXTENDER_SYMBOL) {
14
+ return extend;
15
+ }
16
+ return Reflect.get(target, prop, receiver);
17
+ }
18
+ });
19
+ }
20
+ function getCustomOpenAPIOperation(o) {
21
+ return o[OPERATION_EXTENDER_SYMBOL];
22
+ }
23
+ function applyCustomOpenAPIOperation(operation, contract) {
24
+ const operationCustoms = [];
25
+ for (const errorItem of Object.values(contract["~orpc"].errorMap)) {
26
+ const maybeExtender = errorItem ? getCustomOpenAPIOperation(errorItem) : void 0;
27
+ if (maybeExtender) {
28
+ operationCustoms.push(maybeExtender);
29
+ }
30
+ }
31
+ if (isProcedure(contract)) {
32
+ for (const middleware of contract["~orpc"].middlewares) {
33
+ const maybeExtender = getCustomOpenAPIOperation(middleware);
34
+ if (maybeExtender) {
35
+ operationCustoms.push(maybeExtender);
36
+ }
37
+ }
38
+ }
39
+ let currentOperation = operation;
40
+ for (const custom of operationCustoms) {
41
+ if (typeof custom === "function") {
42
+ currentOperation = custom(currentOperation, contract);
43
+ } else {
44
+ currentOperation = {
45
+ ...currentOperation,
46
+ ...custom
47
+ };
48
+ }
49
+ }
50
+ return currentOperation;
51
+ }
52
+
53
+ const LOGIC_KEYWORDS = [
54
+ "$dynamicRef",
55
+ "$ref",
56
+ "additionalItems",
57
+ "additionalProperties",
58
+ "allOf",
59
+ "anyOf",
60
+ "const",
61
+ "contains",
62
+ "contentEncoding",
63
+ "contentMediaType",
64
+ "contentSchema",
65
+ "dependencies",
66
+ "dependentRequired",
67
+ "dependentSchemas",
68
+ "else",
69
+ "enum",
70
+ "exclusiveMaximum",
71
+ "exclusiveMinimum",
72
+ "format",
73
+ "if",
74
+ "items",
75
+ "maxContains",
76
+ "maximum",
77
+ "maxItems",
78
+ "maxLength",
79
+ "maxProperties",
80
+ "minContains",
81
+ "minimum",
82
+ "minItems",
83
+ "minLength",
84
+ "minProperties",
85
+ "multipleOf",
86
+ "not",
87
+ "oneOf",
88
+ "pattern",
89
+ "patternProperties",
90
+ "prefixItems",
91
+ "properties",
92
+ "propertyNames",
93
+ "required",
94
+ "then",
95
+ "type",
96
+ "unevaluatedItems",
97
+ "unevaluatedProperties",
98
+ "uniqueItems"
99
+ ];
100
+
101
+ function isFileSchema(schema) {
102
+ return isObject(schema) && schema.type === "string" && typeof schema.contentMediaType === "string";
103
+ }
104
+ function isObjectSchema(schema) {
105
+ return isObject(schema) && schema.type === "object";
106
+ }
107
+ function isAnySchema(schema) {
108
+ if (schema === true) {
109
+ return true;
110
+ }
111
+ if (Object.keys(schema).every((k) => !LOGIC_KEYWORDS.includes(k))) {
112
+ return true;
113
+ }
114
+ return false;
115
+ }
116
+ function separateObjectSchema(schema, separatedProperties) {
117
+ if (Object.keys(schema).some((k) => k !== "type" && k !== "properties" && k !== "required" && LOGIC_KEYWORDS.includes(k))) {
118
+ return [{ type: "object" }, schema];
119
+ }
120
+ const matched = { ...schema };
121
+ const rest = { ...schema };
122
+ matched.properties = schema.properties && Object.entries(schema.properties).filter(([key]) => separatedProperties.includes(key)).reduce((acc, [key, value]) => {
123
+ acc[key] = value;
124
+ return acc;
125
+ }, {});
126
+ matched.required = schema.required?.filter((key) => separatedProperties.includes(key));
127
+ matched.examples = schema.examples?.map((example) => {
128
+ if (!isObject(example)) {
129
+ return example;
130
+ }
131
+ return Object.entries(example).reduce((acc, [key, value]) => {
132
+ if (separatedProperties.includes(key)) {
133
+ acc[key] = value;
134
+ }
135
+ return acc;
136
+ }, {});
137
+ });
138
+ rest.properties = schema.properties && Object.entries(schema.properties).filter(([key]) => !separatedProperties.includes(key)).reduce((acc, [key, value]) => {
139
+ acc[key] = value;
140
+ return acc;
141
+ }, {});
142
+ rest.required = schema.required?.filter((key) => !separatedProperties.includes(key));
143
+ rest.examples = schema.examples?.map((example) => {
144
+ if (!isObject(example)) {
145
+ return example;
146
+ }
147
+ return Object.entries(example).reduce((acc, [key, value]) => {
148
+ if (!separatedProperties.includes(key)) {
149
+ acc[key] = value;
150
+ }
151
+ return acc;
152
+ }, {});
153
+ });
154
+ return [matched, rest];
155
+ }
156
+ function filterSchemaBranches(schema, check, matches = []) {
157
+ if (check(schema)) {
158
+ matches.push(schema);
159
+ return [matches, void 0];
160
+ }
161
+ if (isObject(schema)) {
162
+ for (const keyword of ["anyOf", "oneOf"]) {
163
+ if (schema[keyword] && Object.keys(schema).every(
164
+ (k) => k === keyword || !LOGIC_KEYWORDS.includes(k)
165
+ )) {
166
+ const rest = schema[keyword].map((s) => filterSchemaBranches(s, check, matches)[1]).filter((v) => !!v);
167
+ if (rest.length === 1 && typeof rest[0] === "object") {
168
+ return [matches, { ...schema, [keyword]: void 0, ...rest[0] }];
169
+ }
170
+ return [matches, { ...schema, [keyword]: rest }];
171
+ }
172
+ }
173
+ }
174
+ return [matches, schema];
175
+ }
176
+ function applySchemaOptionality(required, schema) {
177
+ if (required) {
178
+ return schema;
179
+ }
180
+ return {
181
+ anyOf: [
182
+ schema,
183
+ { not: {} }
184
+ ]
185
+ };
186
+ }
187
+ function expandUnionSchema(schema) {
188
+ if (typeof schema === "object") {
189
+ for (const keyword of ["anyOf", "oneOf"]) {
190
+ if (schema[keyword] && Object.keys(schema).every(
191
+ (k) => k === keyword || !LOGIC_KEYWORDS.includes(k)
192
+ )) {
193
+ return schema[keyword].flatMap((s) => expandUnionSchema(s));
194
+ }
195
+ }
196
+ }
197
+ return [schema];
198
+ }
199
+ function expandArrayableSchema(schema) {
200
+ const schemas = expandUnionSchema(schema);
201
+ if (schemas.length !== 2) {
202
+ return void 0;
203
+ }
204
+ const arraySchema = schemas.find(
205
+ (s) => typeof s === "object" && s.type === "array" && Object.keys(s).filter((k) => LOGIC_KEYWORDS.includes(k)).every((k) => k === "type" || k === "items")
206
+ );
207
+ if (arraySchema === void 0) {
208
+ return void 0;
209
+ }
210
+ const items1 = arraySchema.items;
211
+ const items2 = schemas.find((s) => s !== arraySchema);
212
+ if (stringifyJSON(items1) !== stringifyJSON(items2)) {
213
+ return void 0;
214
+ }
215
+ return [items2, arraySchema];
216
+ }
217
+ const PRIMITIVE_SCHEMA_TYPES = /* @__PURE__ */ new Set([
218
+ TypeName.String,
219
+ TypeName.Number,
220
+ TypeName.Integer,
221
+ TypeName.Boolean,
222
+ TypeName.Null
223
+ ]);
224
+ function isPrimitiveSchema(schema) {
225
+ return expandUnionSchema(schema).every((s) => {
226
+ if (typeof s === "boolean") {
227
+ return false;
228
+ }
229
+ if (typeof s.type === "string" && PRIMITIVE_SCHEMA_TYPES.has(s.type)) {
230
+ return true;
231
+ }
232
+ if (s.const !== void 0) {
233
+ return true;
234
+ }
235
+ return false;
236
+ });
237
+ }
238
+
239
+ function toOpenAPIPath(path) {
240
+ return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/{$1}");
241
+ }
242
+ function toOpenAPIMethod(method) {
243
+ return method.toLocaleLowerCase();
244
+ }
245
+ function toOpenAPIContent(schema) {
246
+ const content = {};
247
+ const [matches, restSchema] = filterSchemaBranches(schema, isFileSchema);
248
+ for (const file of matches) {
249
+ content[file.contentMediaType] = {
250
+ schema: toOpenAPISchema(file)
251
+ };
252
+ }
253
+ if (restSchema !== void 0) {
254
+ content["application/json"] = {
255
+ schema: toOpenAPISchema(restSchema)
256
+ };
257
+ const isStillHasFileSchema = findDeepMatches((v) => isObject(v) && isFileSchema(v), restSchema).values.length > 0;
258
+ if (isStillHasFileSchema) {
259
+ content["multipart/form-data"] = {
260
+ schema: toOpenAPISchema(restSchema)
261
+ };
262
+ }
263
+ }
264
+ return content;
265
+ }
266
+ function toOpenAPIEventIteratorContent([yieldsRequired, yieldsSchema], [returnsRequired, returnsSchema]) {
267
+ return {
268
+ "text/event-stream": {
269
+ schema: toOpenAPISchema({
270
+ oneOf: [
271
+ {
272
+ type: "object",
273
+ properties: {
274
+ event: { const: "message" },
275
+ data: yieldsSchema,
276
+ id: { type: "string" },
277
+ retry: { type: "number" }
278
+ },
279
+ required: yieldsRequired ? ["event", "data"] : ["event"]
280
+ },
281
+ {
282
+ type: "object",
283
+ properties: {
284
+ event: { const: "done" },
285
+ data: returnsSchema,
286
+ id: { type: "string" },
287
+ retry: { type: "number" }
288
+ },
289
+ required: returnsRequired ? ["event", "data"] : ["event"]
290
+ },
291
+ {
292
+ type: "object",
293
+ properties: {
294
+ event: { const: "error" },
295
+ data: {},
296
+ id: { type: "string" },
297
+ retry: { type: "number" }
298
+ },
299
+ required: ["event"]
300
+ }
301
+ ]
302
+ })
303
+ }
304
+ };
305
+ }
306
+ function toOpenAPIParameters(schema, parameterIn) {
307
+ const parameters = [];
308
+ for (const key in schema.properties) {
309
+ const keySchema = schema.properties[key];
310
+ let isDeepObjectStyle = true;
311
+ if (parameterIn !== "query") {
312
+ isDeepObjectStyle = false;
313
+ } else if (isPrimitiveSchema(keySchema)) {
314
+ isDeepObjectStyle = false;
315
+ } else {
316
+ const [item] = expandArrayableSchema(keySchema) ?? [];
317
+ if (item !== void 0 && isPrimitiveSchema(item)) {
318
+ isDeepObjectStyle = false;
319
+ }
320
+ }
321
+ parameters.push({
322
+ name: key,
323
+ in: parameterIn,
324
+ required: schema.required?.includes(key),
325
+ schema: toOpenAPISchema(keySchema),
326
+ style: isDeepObjectStyle ? "deepObject" : void 0,
327
+ explode: isDeepObjectStyle ? true : void 0,
328
+ allowEmptyValue: parameterIn === "query" ? true : void 0,
329
+ allowReserved: parameterIn === "query" ? true : void 0
330
+ });
331
+ }
332
+ return parameters;
333
+ }
334
+ function checkParamsSchema(schema, params) {
335
+ const properties = Object.keys(schema.properties ?? {});
336
+ const required = schema.required ?? [];
337
+ if (properties.length !== params.length || properties.some((v) => !params.includes(v))) {
338
+ return false;
339
+ }
340
+ if (required.length !== params.length || required.some((v) => !params.includes(v))) {
341
+ return false;
342
+ }
343
+ return true;
344
+ }
345
+ function toOpenAPISchema(schema) {
346
+ return schema === true ? {} : schema === false ? { not: {} } : schema;
347
+ }
348
+
349
+ class CompositeSchemaConverter {
350
+ converters;
351
+ constructor(converters) {
352
+ this.converters = converters;
353
+ }
354
+ async convert(schema, options) {
355
+ for (const converter of this.converters) {
356
+ if (await converter.condition(schema, options)) {
357
+ return converter.convert(schema, options);
358
+ }
359
+ }
360
+ return [false, {}];
361
+ }
362
+ }
363
+
364
+ class OpenAPIGeneratorError extends Error {
365
+ }
366
+ class OpenAPIGenerator {
367
+ serializer;
368
+ converter;
369
+ constructor(options = {}) {
370
+ this.serializer = new StandardOpenAPIJsonSerializer(options);
371
+ this.converter = new CompositeSchemaConverter(toArray(options.schemaConverters));
372
+ }
373
+ /**
374
+ * Generates OpenAPI specifications from oRPC routers/contracts.
375
+ *
376
+ * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
377
+ */
378
+ async generate(router, options = {}) {
379
+ const exclude = options.exclude ?? (() => false);
380
+ const doc = {
381
+ ...clone(options),
382
+ info: options.info ?? { title: "API Reference", version: "0.0.0" },
383
+ openapi: "3.1.1",
384
+ exclude: void 0
385
+ };
386
+ const contracts = [];
387
+ await resolveContractProcedures({ path: [], router }, ({ contract, path }) => {
388
+ if (!exclude(contract, path)) {
389
+ contracts.push({ contract, path });
390
+ }
391
+ });
392
+ const errors = [];
393
+ for (const { contract, path } of contracts) {
394
+ const operationId = path.join(".");
395
+ try {
396
+ const def = contract["~orpc"];
397
+ const method = toOpenAPIMethod(fallbackContractConfig("defaultMethod", def.route.method));
398
+ const httpPath = toOpenAPIPath(def.route.path ?? toHttpPath(path));
399
+ let operationObjectRef;
400
+ if (def.route.spec !== void 0) {
401
+ operationObjectRef = def.route.spec;
402
+ } else {
403
+ operationObjectRef = {
404
+ operationId,
405
+ summary: def.route.summary,
406
+ description: def.route.description,
407
+ deprecated: def.route.deprecated,
408
+ tags: def.route.tags?.map((tag) => tag)
409
+ };
410
+ await this.#request(operationObjectRef, def);
411
+ await this.#successResponse(operationObjectRef, def);
412
+ await this.#errorResponse(operationObjectRef, def);
413
+ }
414
+ doc.paths ??= {};
415
+ doc.paths[httpPath] ??= {};
416
+ doc.paths[httpPath][method] = applyCustomOpenAPIOperation(operationObjectRef, contract);
417
+ } catch (e) {
418
+ if (!(e instanceof OpenAPIGeneratorError)) {
419
+ throw e;
420
+ }
421
+ errors.push(
422
+ `[OpenAPIGenerator] Error occurred while generating OpenAPI for procedure at path: ${operationId}
423
+ ${e.message}`
424
+ );
425
+ }
426
+ }
427
+ if (errors.length) {
428
+ throw new OpenAPIGeneratorError(
429
+ `Some error occurred during OpenAPI generation:
430
+
431
+ ${errors.join("\n\n")}`
432
+ );
433
+ }
434
+ return this.serializer.serialize(doc)[0];
435
+ }
436
+ async #request(ref, def) {
437
+ const method = fallbackContractConfig("defaultMethod", def.route.method);
438
+ const details = getEventIteratorSchemaDetails(def.inputSchema);
439
+ if (details) {
440
+ ref.requestBody = {
441
+ required: true,
442
+ content: toOpenAPIEventIteratorContent(
443
+ await this.converter.convert(details.yields, { strategy: "input" }),
444
+ await this.converter.convert(details.returns, { strategy: "input" })
445
+ )
446
+ };
447
+ return;
448
+ }
449
+ const dynamicParams = getDynamicParams(def.route.path)?.map((v) => v.name);
450
+ const inputStructure = fallbackContractConfig("defaultInputStructure", def.route.inputStructure);
451
+ let [required, schema] = await this.converter.convert(def.inputSchema, { strategy: "input" });
452
+ if (isAnySchema(schema) && !dynamicParams?.length) {
453
+ return;
454
+ }
455
+ if (inputStructure === "compact") {
456
+ if (dynamicParams?.length) {
457
+ const error2 = new OpenAPIGeneratorError(
458
+ 'When input structure is "compact", and path has dynamic params, input schema must be an object with all dynamic params as required.'
459
+ );
460
+ if (!isObjectSchema(schema)) {
461
+ throw error2;
462
+ }
463
+ const [paramsSchema, rest] = separateObjectSchema(schema, dynamicParams);
464
+ schema = rest;
465
+ required = rest.required ? rest.required.length !== 0 : false;
466
+ if (!checkParamsSchema(paramsSchema, dynamicParams)) {
467
+ throw error2;
468
+ }
469
+ ref.parameters ??= [];
470
+ ref.parameters.push(...toOpenAPIParameters(paramsSchema, "path"));
471
+ }
472
+ if (method === "GET") {
473
+ if (!isObjectSchema(schema)) {
474
+ throw new OpenAPIGeneratorError(
475
+ 'When method is "GET", input schema must satisfy: object | any | unknown'
476
+ );
477
+ }
478
+ ref.parameters ??= [];
479
+ ref.parameters.push(...toOpenAPIParameters(schema, "query"));
480
+ } else {
481
+ ref.requestBody = {
482
+ required,
483
+ content: toOpenAPIContent(schema)
484
+ };
485
+ }
486
+ return;
487
+ }
488
+ const error = new OpenAPIGeneratorError(
489
+ 'When input structure is "detailed", input schema must satisfy: { params?: Record<string, unknown>, query?: Record<string, unknown>, headers?: Record<string, unknown>, body?: unknown }'
490
+ );
491
+ if (!isObjectSchema(schema)) {
492
+ throw error;
493
+ }
494
+ if (dynamicParams?.length && (schema.properties?.params === void 0 || !isObjectSchema(schema.properties.params) || !checkParamsSchema(schema.properties.params, dynamicParams))) {
495
+ throw new OpenAPIGeneratorError(
496
+ 'When input structure is "detailed" and path has dynamic params, the "params" schema must be an object with all dynamic params as required.'
497
+ );
498
+ }
499
+ for (const from of ["params", "query", "headers"]) {
500
+ const fromSchema = schema.properties?.[from];
501
+ if (fromSchema !== void 0) {
502
+ if (!isObjectSchema(fromSchema)) {
503
+ throw error;
504
+ }
505
+ const parameterIn = from === "params" ? "path" : from === "headers" ? "header" : "query";
506
+ ref.parameters ??= [];
507
+ ref.parameters.push(...toOpenAPIParameters(fromSchema, parameterIn));
508
+ }
509
+ }
510
+ if (schema.properties?.body !== void 0) {
511
+ ref.requestBody = {
512
+ required: schema.required?.includes("body"),
513
+ content: toOpenAPIContent(schema.properties.body)
514
+ };
515
+ }
516
+ }
517
+ async #successResponse(ref, def) {
518
+ const outputSchema = def.outputSchema;
519
+ const status = fallbackContractConfig("defaultSuccessStatus", def.route.successStatus);
520
+ const description = fallbackContractConfig("defaultSuccessDescription", def.route?.successDescription);
521
+ const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(outputSchema);
522
+ const outputStructure = fallbackContractConfig("defaultOutputStructure", def.route.outputStructure);
523
+ if (eventIteratorSchemaDetails) {
524
+ ref.responses ??= {};
525
+ ref.responses[status] = {
526
+ description,
527
+ content: toOpenAPIEventIteratorContent(
528
+ await this.converter.convert(eventIteratorSchemaDetails.yields, { strategy: "output" }),
529
+ await this.converter.convert(eventIteratorSchemaDetails.returns, { strategy: "output" })
530
+ )
531
+ };
532
+ return;
533
+ }
534
+ const [required, json] = await this.converter.convert(outputSchema, { strategy: "output" });
535
+ if (outputStructure === "compact") {
536
+ ref.responses ??= {};
537
+ ref.responses[status] = {
538
+ description
539
+ };
540
+ ref.responses[status].content = toOpenAPIContent(applySchemaOptionality(required, json));
541
+ return;
542
+ }
543
+ const handledStatuses = /* @__PURE__ */ new Set();
544
+ for (const item of expandUnionSchema(json)) {
545
+ const error = new OpenAPIGeneratorError(`
546
+ When output structure is "detailed", output schema must satisfy:
547
+ {
548
+ status?: number, // must be a literal number and in the range of 200-399
549
+ headers?: Record<string, unknown>,
550
+ body?: unknown
551
+ }
552
+
553
+ But got: ${stringifyJSON(item)}
554
+ `);
555
+ if (!isObjectSchema(item)) {
556
+ throw error;
557
+ }
558
+ let schemaStatus;
559
+ let schemaDescription;
560
+ if (item.properties?.status !== void 0) {
561
+ if (typeof item.properties.status !== "object" || item.properties.status.const === void 0 || typeof item.properties.status.const !== "number" || !Number.isInteger(item.properties.status.const) || isORPCErrorStatus(item.properties.status.const)) {
562
+ throw error;
563
+ }
564
+ schemaStatus = item.properties.status.const;
565
+ schemaDescription = item.properties.status.description;
566
+ }
567
+ const itemStatus = schemaStatus ?? status;
568
+ const itemDescription = schemaDescription ?? description;
569
+ if (handledStatuses.has(itemStatus)) {
570
+ throw new OpenAPIGeneratorError(`
571
+ When output structure is "detailed", each success status must be unique.
572
+ But got status: ${itemStatus} used more than once.
573
+ `);
574
+ }
575
+ handledStatuses.add(itemStatus);
576
+ ref.responses ??= {};
577
+ ref.responses[itemStatus] = {
578
+ description: itemDescription
579
+ };
580
+ if (item.properties?.headers !== void 0) {
581
+ if (!isObjectSchema(item.properties.headers)) {
582
+ throw error;
583
+ }
584
+ for (const key in item.properties.headers.properties) {
585
+ const headerSchema = item.properties.headers.properties[key];
586
+ if (headerSchema !== void 0) {
587
+ ref.responses[itemStatus].headers ??= {};
588
+ ref.responses[itemStatus].headers[key] = {
589
+ schema: toOpenAPISchema(headerSchema),
590
+ required: item.properties.headers.required?.includes(key)
591
+ };
592
+ }
593
+ }
594
+ }
595
+ if (item.properties?.body !== void 0) {
596
+ ref.responses[itemStatus].content = toOpenAPIContent(
597
+ applySchemaOptionality(item.required?.includes("body") ?? false, item.properties.body)
598
+ );
599
+ }
600
+ }
601
+ }
602
+ async #errorResponse(ref, def) {
603
+ const errorMap = def.errorMap;
604
+ const errors = {};
605
+ for (const code in errorMap) {
606
+ const config = errorMap[code];
607
+ if (!config) {
608
+ continue;
609
+ }
610
+ const status = fallbackORPCErrorStatus(code, config.status);
611
+ const message = fallbackORPCErrorMessage(code, config.message);
612
+ const [dataRequired, dataSchema] = await this.converter.convert(config.data, { strategy: "output" });
613
+ errors[status] ??= [];
614
+ errors[status].push({
615
+ type: "object",
616
+ properties: {
617
+ defined: { const: true },
618
+ code: { const: code },
619
+ status: { const: status },
620
+ message: { type: "string", default: message },
621
+ data: dataSchema
622
+ },
623
+ required: dataRequired ? ["defined", "code", "status", "message", "data"] : ["defined", "code", "status", "message"]
624
+ });
625
+ }
626
+ ref.responses ??= {};
627
+ for (const status in errors) {
628
+ const schemas = errors[status];
629
+ ref.responses[status] = {
630
+ description: status,
631
+ content: toOpenAPIContent({
632
+ oneOf: [
633
+ ...schemas,
634
+ {
635
+ type: "object",
636
+ properties: {
637
+ defined: { const: false },
638
+ code: { type: "string" },
639
+ status: { type: "number" },
640
+ message: { type: "string" },
641
+ data: {}
642
+ },
643
+ required: ["defined", "code", "status", "message"]
644
+ }
645
+ ]
646
+ })
647
+ };
648
+ }
649
+ }
650
+ }
651
+
652
+ 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, separateObjectSchema as s, toOpenAPIPath as t };
@@ -0,0 +1,52 @@
1
+ import { AnySchema, OpenAPI, AnyContractProcedure, AnyContractRouter } from '@orpc/contract';
2
+ import { StandardOpenAPIJsonSerializerOptions } from '@orpc/openapi-client/standard';
3
+ import { AnyProcedure, AnyRouter } from '@orpc/server';
4
+ import { Promisable } from '@orpc/shared';
5
+ import { JSONSchema } from 'json-schema-typed/draft-2020-12';
6
+
7
+ interface SchemaConvertOptions {
8
+ strategy: 'input' | 'output';
9
+ }
10
+ interface SchemaConverter {
11
+ convert(schema: AnySchema | undefined, options: SchemaConvertOptions): Promisable<[required: boolean, jsonSchema: JSONSchema]>;
12
+ }
13
+ interface ConditionalSchemaConverter extends SchemaConverter {
14
+ condition(schema: AnySchema | undefined, options: SchemaConvertOptions): Promisable<boolean>;
15
+ }
16
+ declare class CompositeSchemaConverter implements SchemaConverter {
17
+ private readonly converters;
18
+ constructor(converters: ConditionalSchemaConverter[]);
19
+ convert(schema: AnySchema | undefined, options: SchemaConvertOptions): Promise<[required: boolean, jsonSchema: JSONSchema]>;
20
+ }
21
+
22
+ interface OpenAPIGeneratorOptions extends StandardOpenAPIJsonSerializerOptions {
23
+ schemaConverters?: ConditionalSchemaConverter[];
24
+ }
25
+ interface OpenAPIGeneratorGenerateOptions extends Partial<Omit<OpenAPI.Document, 'openapi'>> {
26
+ /**
27
+ * Exclude procedures from the OpenAPI specification.
28
+ *
29
+ * @default () => false
30
+ */
31
+ exclude?: (procedure: AnyProcedure | AnyContractProcedure, path: readonly string[]) => boolean;
32
+ }
33
+ /**
34
+ * The generator that converts oRPC routers/contracts to OpenAPI specifications.
35
+ *
36
+ * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
37
+ */
38
+ declare class OpenAPIGenerator {
39
+ #private;
40
+ private readonly serializer;
41
+ private readonly converter;
42
+ constructor(options?: OpenAPIGeneratorOptions);
43
+ /**
44
+ * Generates OpenAPI specifications from oRPC routers/contracts.
45
+ *
46
+ * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
47
+ */
48
+ generate(router: AnyContractRouter | AnyRouter, options?: OpenAPIGeneratorGenerateOptions): Promise<OpenAPI.Document>;
49
+ }
50
+
51
+ export { OpenAPIGenerator as b, CompositeSchemaConverter as d };
52
+ export type { ConditionalSchemaConverter as C, OpenAPIGeneratorOptions as O, SchemaConvertOptions as S, OpenAPIGeneratorGenerateOptions as a, SchemaConverter as c };