@orpc/openapi 1.0.3 → 1.1.0

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.
package/dist/index.d.mts CHANGED
@@ -1,12 +1,13 @@
1
- import { AnyContractProcedure, AnySchema, AnyContractRouter } from '@orpc/contract';
1
+ import { AnyContractProcedure } from '@orpc/contract';
2
2
  import { OpenAPIV3_1 } from 'openapi-types';
3
3
  export { OpenAPIV3_1 as OpenAPI } from 'openapi-types';
4
- import { StandardOpenAPIJsonSerializerOptions } from '@orpc/openapi-client/standard';
5
- import { AnyRouter } from '@orpc/server';
6
- import { Promisable } from '@orpc/shared';
4
+ export { d as CompositeSchemaConverter, C as ConditionalSchemaConverter, b as OpenAPIGenerator, a as OpenAPIGeneratorGenerateOptions, O as OpenAPIGeneratorOptions, S as SchemaConvertOptions, c as SchemaConverter } from './shared/openapi.DP97kr00.mjs';
5
+ import { HTTPPath, HTTPMethod } from '@orpc/client';
7
6
  import { JSONSchema } from 'json-schema-typed/draft-2020-12';
8
7
  export { JSONSchema, Format as JSONSchemaFormat } from 'json-schema-typed/draft-2020-12';
9
- import { HTTPPath, HTTPMethod } from '@orpc/client';
8
+ import '@orpc/openapi-client/standard';
9
+ import '@orpc/server';
10
+ import '@orpc/shared';
10
11
 
11
12
  type OverrideOperationValue = Partial<OpenAPIV3_1.OperationObject> | ((current: OpenAPIV3_1.OperationObject, procedure: AnyContractProcedure) => OpenAPIV3_1.OperationObject);
12
13
  /**
@@ -36,42 +37,6 @@ type FileSchema = JSONSchema & {
36
37
  */
37
38
  declare const LOGIC_KEYWORDS: string[];
38
39
 
39
- interface SchemaConvertOptions {
40
- strategy: 'input' | 'output';
41
- }
42
- interface SchemaConverter {
43
- convert(schema: AnySchema | undefined, options: SchemaConvertOptions): Promisable<[required: boolean, jsonSchema: JSONSchema]>;
44
- }
45
- interface ConditionalSchemaConverter extends SchemaConverter {
46
- condition(schema: AnySchema | undefined, options: SchemaConvertOptions): Promisable<boolean>;
47
- }
48
- declare class CompositeSchemaConverter implements SchemaConverter {
49
- private readonly converters;
50
- constructor(converters: ConditionalSchemaConverter[]);
51
- convert(schema: AnySchema | undefined, options: SchemaConvertOptions): Promise<[required: boolean, jsonSchema: JSONSchema]>;
52
- }
53
-
54
- interface OpenAPIGeneratorOptions extends StandardOpenAPIJsonSerializerOptions {
55
- schemaConverters?: ConditionalSchemaConverter[];
56
- }
57
- /**
58
- * The generator that converts oRPC routers/contracts to OpenAPI specifications.
59
- *
60
- * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
61
- */
62
- declare class OpenAPIGenerator {
63
- #private;
64
- private readonly serializer;
65
- private readonly converter;
66
- constructor(options?: OpenAPIGeneratorOptions);
67
- /**
68
- * Generates OpenAPI specifications from oRPC routers/contracts.
69
- *
70
- * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
71
- */
72
- generate(router: AnyContractRouter | AnyRouter, base: Omit<OpenAPIV3_1.Document, 'openapi'>): Promise<OpenAPIV3_1.Document>;
73
- }
74
-
75
40
  /**
76
41
  * @internal
77
42
  */
@@ -127,5 +92,5 @@ declare const oo: {
127
92
  spec: typeof customOpenAPIOperation;
128
93
  };
129
94
 
130
- export { CompositeSchemaConverter, LOGIC_KEYWORDS, OpenAPIGenerator, applyCustomOpenAPIOperation, applySchemaOptionality, checkParamsSchema, customOpenAPIOperation, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, oo, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
131
- export type { ConditionalSchemaConverter, FileSchema, ObjectSchema, OpenAPIGeneratorOptions, OverrideOperationValue, SchemaConvertOptions, SchemaConverter };
95
+ export { LOGIC_KEYWORDS, applyCustomOpenAPIOperation, applySchemaOptionality, checkParamsSchema, customOpenAPIOperation, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, oo, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
96
+ export type { FileSchema, ObjectSchema, OverrideOperationValue };
package/dist/index.d.ts CHANGED
@@ -1,12 +1,13 @@
1
- import { AnyContractProcedure, AnySchema, AnyContractRouter } from '@orpc/contract';
1
+ import { AnyContractProcedure } from '@orpc/contract';
2
2
  import { OpenAPIV3_1 } from 'openapi-types';
3
3
  export { OpenAPIV3_1 as OpenAPI } from 'openapi-types';
4
- import { StandardOpenAPIJsonSerializerOptions } from '@orpc/openapi-client/standard';
5
- import { AnyRouter } from '@orpc/server';
6
- import { Promisable } from '@orpc/shared';
4
+ export { d as CompositeSchemaConverter, C as ConditionalSchemaConverter, b as OpenAPIGenerator, a as OpenAPIGeneratorGenerateOptions, O as OpenAPIGeneratorOptions, S as SchemaConvertOptions, c as SchemaConverter } from './shared/openapi.DP97kr00.js';
5
+ import { HTTPPath, HTTPMethod } from '@orpc/client';
7
6
  import { JSONSchema } from 'json-schema-typed/draft-2020-12';
8
7
  export { JSONSchema, Format as JSONSchemaFormat } from 'json-schema-typed/draft-2020-12';
9
- import { HTTPPath, HTTPMethod } from '@orpc/client';
8
+ import '@orpc/openapi-client/standard';
9
+ import '@orpc/server';
10
+ import '@orpc/shared';
10
11
 
11
12
  type OverrideOperationValue = Partial<OpenAPIV3_1.OperationObject> | ((current: OpenAPIV3_1.OperationObject, procedure: AnyContractProcedure) => OpenAPIV3_1.OperationObject);
12
13
  /**
@@ -36,42 +37,6 @@ type FileSchema = JSONSchema & {
36
37
  */
37
38
  declare const LOGIC_KEYWORDS: string[];
38
39
 
39
- interface SchemaConvertOptions {
40
- strategy: 'input' | 'output';
41
- }
42
- interface SchemaConverter {
43
- convert(schema: AnySchema | undefined, options: SchemaConvertOptions): Promisable<[required: boolean, jsonSchema: JSONSchema]>;
44
- }
45
- interface ConditionalSchemaConverter extends SchemaConverter {
46
- condition(schema: AnySchema | undefined, options: SchemaConvertOptions): Promisable<boolean>;
47
- }
48
- declare class CompositeSchemaConverter implements SchemaConverter {
49
- private readonly converters;
50
- constructor(converters: ConditionalSchemaConverter[]);
51
- convert(schema: AnySchema | undefined, options: SchemaConvertOptions): Promise<[required: boolean, jsonSchema: JSONSchema]>;
52
- }
53
-
54
- interface OpenAPIGeneratorOptions extends StandardOpenAPIJsonSerializerOptions {
55
- schemaConverters?: ConditionalSchemaConverter[];
56
- }
57
- /**
58
- * The generator that converts oRPC routers/contracts to OpenAPI specifications.
59
- *
60
- * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
61
- */
62
- declare class OpenAPIGenerator {
63
- #private;
64
- private readonly serializer;
65
- private readonly converter;
66
- constructor(options?: OpenAPIGeneratorOptions);
67
- /**
68
- * Generates OpenAPI specifications from oRPC routers/contracts.
69
- *
70
- * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
71
- */
72
- generate(router: AnyContractRouter | AnyRouter, base: Omit<OpenAPIV3_1.Document, 'openapi'>): Promise<OpenAPIV3_1.Document>;
73
- }
74
-
75
40
  /**
76
41
  * @internal
77
42
  */
@@ -127,5 +92,5 @@ declare const oo: {
127
92
  spec: typeof customOpenAPIOperation;
128
93
  };
129
94
 
130
- export { CompositeSchemaConverter, LOGIC_KEYWORDS, OpenAPIGenerator, applyCustomOpenAPIOperation, applySchemaOptionality, checkParamsSchema, customOpenAPIOperation, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, oo, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
131
- export type { ConditionalSchemaConverter, FileSchema, ObjectSchema, OpenAPIGeneratorOptions, OverrideOperationValue, SchemaConvertOptions, SchemaConverter };
95
+ export { LOGIC_KEYWORDS, applyCustomOpenAPIOperation, applySchemaOptionality, checkParamsSchema, customOpenAPIOperation, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, oo, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
96
+ export type { FileSchema, ObjectSchema, OverrideOperationValue };
package/dist/index.mjs CHANGED
@@ -1,545 +1,15 @@
1
- import { isProcedure, resolveContractProcedures } from '@orpc/server';
2
- import { fallbackORPCErrorStatus, fallbackORPCErrorMessage } from '@orpc/client';
3
- import { toHttpPath } from '@orpc/client/standard';
4
- import { fallbackContractConfig, getEventIteratorSchemaDetails } from '@orpc/contract';
5
- import { standardizeHTTPPath, StandardOpenAPIJsonSerializer, getDynamicParams } from '@orpc/openapi-client/standard';
6
- import { isObject, findDeepMatches, toArray, clone } from '@orpc/shared';
1
+ import { c as customOpenAPIOperation } from './shared/openapi.fMEQd3Yd.mjs';
2
+ export { C as CompositeSchemaConverter, L as LOGIC_KEYWORDS, O as OpenAPIGenerator, a as applyCustomOpenAPIOperation, n as applySchemaOptionality, h as checkParamsSchema, m as filterSchemaBranches, g as getCustomOpenAPIOperation, l as isAnySchema, j as isFileSchema, k as isObjectSchema, s as separateObjectSchema, d as toOpenAPIContent, e as toOpenAPIEventIteratorContent, b as toOpenAPIMethod, f as toOpenAPIParameters, t as toOpenAPIPath, i as toOpenAPISchema } from './shared/openapi.fMEQd3Yd.mjs';
7
3
  export { Format as JSONSchemaFormat } 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
-
188
- function toOpenAPIPath(path) {
189
- return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/{$1}");
190
- }
191
- function toOpenAPIMethod(method) {
192
- return method.toLocaleLowerCase();
193
- }
194
- function toOpenAPIContent(schema) {
195
- const content = {};
196
- const [matches, restSchema] = filterSchemaBranches(schema, isFileSchema);
197
- for (const file of matches) {
198
- content[file.contentMediaType] = {
199
- schema: toOpenAPISchema(file)
200
- };
201
- }
202
- if (restSchema !== void 0) {
203
- content["application/json"] = {
204
- schema: toOpenAPISchema(restSchema)
205
- };
206
- const isStillHasFileSchema = findDeepMatches((v) => isObject(v) && isFileSchema(v), restSchema).values.length > 0;
207
- if (isStillHasFileSchema) {
208
- content["multipart/form-data"] = {
209
- schema: toOpenAPISchema(restSchema)
210
- };
211
- }
212
- }
213
- return content;
214
- }
215
- function toOpenAPIEventIteratorContent([yieldsRequired, yieldsSchema], [returnsRequired, returnsSchema]) {
216
- return {
217
- "text/event-stream": {
218
- schema: toOpenAPISchema({
219
- oneOf: [
220
- {
221
- type: "object",
222
- properties: {
223
- event: { const: "message" },
224
- data: yieldsSchema,
225
- id: { type: "string" },
226
- retry: { type: "number" }
227
- },
228
- required: yieldsRequired ? ["event", "data"] : ["event"]
229
- },
230
- {
231
- type: "object",
232
- properties: {
233
- event: { const: "done" },
234
- data: returnsSchema,
235
- id: { type: "string" },
236
- retry: { type: "number" }
237
- },
238
- required: returnsRequired ? ["event", "data"] : ["event"]
239
- },
240
- {
241
- type: "object",
242
- properties: {
243
- event: { const: "error" },
244
- data: {},
245
- id: { type: "string" },
246
- retry: { type: "number" }
247
- },
248
- required: ["event"]
249
- }
250
- ]
251
- })
252
- }
253
- };
254
- }
255
- function toOpenAPIParameters(schema, parameterIn) {
256
- const parameters = [];
257
- for (const key in schema.properties) {
258
- const keySchema = schema.properties[key];
259
- parameters.push({
260
- name: key,
261
- in: parameterIn,
262
- required: schema.required?.includes(key),
263
- style: parameterIn === "query" ? "deepObject" : void 0,
264
- explode: parameterIn === "query" ? true : void 0,
265
- schema: toOpenAPISchema(keySchema)
266
- });
267
- }
268
- return parameters;
269
- }
270
- function checkParamsSchema(schema, params) {
271
- const properties = Object.keys(schema.properties ?? {});
272
- const required = schema.required ?? [];
273
- if (properties.length !== params.length || properties.some((v) => !params.includes(v))) {
274
- return false;
275
- }
276
- if (required.length !== params.length || required.some((v) => !params.includes(v))) {
277
- return false;
278
- }
279
- return true;
280
- }
281
- function toOpenAPISchema(schema) {
282
- return schema === true ? {} : schema === false ? { not: {} } : schema;
283
- }
284
-
285
- class CompositeSchemaConverter {
286
- converters;
287
- constructor(converters) {
288
- this.converters = converters;
289
- }
290
- async convert(schema, options) {
291
- for (const converter of this.converters) {
292
- if (await converter.condition(schema, options)) {
293
- return converter.convert(schema, options);
294
- }
295
- }
296
- return [false, {}];
297
- }
298
- }
299
-
300
- class OpenAPIGeneratorError extends Error {
301
- }
302
- class OpenAPIGenerator {
303
- serializer;
304
- converter;
305
- constructor(options = {}) {
306
- this.serializer = new StandardOpenAPIJsonSerializer(options);
307
- this.converter = new CompositeSchemaConverter(toArray(options.schemaConverters));
308
- }
309
- /**
310
- * Generates OpenAPI specifications from oRPC routers/contracts.
311
- *
312
- * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
313
- */
314
- async generate(router, base) {
315
- const doc = clone(base);
316
- doc.openapi = "3.1.1";
317
- const contracts = [];
318
- await resolveContractProcedures({ path: [], router }, ({ contract, path }) => {
319
- contracts.push({ contract, path });
320
- });
321
- const errors = [];
322
- for (const { contract, path } of contracts) {
323
- const operationId = path.join(".");
324
- try {
325
- const def = contract["~orpc"];
326
- const method = toOpenAPIMethod(fallbackContractConfig("defaultMethod", def.route.method));
327
- const httpPath = toOpenAPIPath(def.route.path ?? toHttpPath(path));
328
- const operationObjectRef = {
329
- operationId,
330
- summary: def.route.summary,
331
- description: def.route.description,
332
- deprecated: def.route.deprecated,
333
- tags: def.route.tags?.map((tag) => tag)
334
- };
335
- await this.#request(operationObjectRef, def);
336
- await this.#successResponse(operationObjectRef, def);
337
- await this.#errorResponse(operationObjectRef, def);
338
- doc.paths ??= {};
339
- doc.paths[httpPath] ??= {};
340
- doc.paths[httpPath][method] = applyCustomOpenAPIOperation(operationObjectRef, contract);
341
- } catch (e) {
342
- if (!(e instanceof OpenAPIGeneratorError)) {
343
- throw e;
344
- }
345
- errors.push(
346
- `[OpenAPIGenerator] Error occurred while generating OpenAPI for procedure at path: ${operationId}
347
- ${e.message}`
348
- );
349
- }
350
- }
351
- if (errors.length) {
352
- throw new OpenAPIGeneratorError(
353
- `Some error occurred during OpenAPI generation:
354
-
355
- ${errors.join("\n\n")}`
356
- );
357
- }
358
- return this.serializer.serialize(doc)[0];
359
- }
360
- async #request(ref, def) {
361
- const method = fallbackContractConfig("defaultMethod", def.route.method);
362
- const details = getEventIteratorSchemaDetails(def.inputSchema);
363
- if (details) {
364
- ref.requestBody = {
365
- required: true,
366
- content: toOpenAPIEventIteratorContent(
367
- await this.converter.convert(details.yields, { strategy: "input" }),
368
- await this.converter.convert(details.returns, { strategy: "input" })
369
- )
370
- };
371
- return;
372
- }
373
- const dynamicParams = getDynamicParams(def.route.path)?.map((v) => v.name);
374
- const inputStructure = fallbackContractConfig("defaultInputStructure", def.route.inputStructure);
375
- let [required, schema] = await this.converter.convert(def.inputSchema, { strategy: "input" });
376
- if (isAnySchema(schema) && !dynamicParams?.length) {
377
- return;
378
- }
379
- if (inputStructure === "compact") {
380
- if (dynamicParams?.length) {
381
- const error2 = new OpenAPIGeneratorError(
382
- 'When input structure is "compact", and path has dynamic params, input schema must be an object with all dynamic params as required.'
383
- );
384
- if (!isObjectSchema(schema)) {
385
- throw error2;
386
- }
387
- const [paramsSchema, rest] = separateObjectSchema(schema, dynamicParams);
388
- schema = rest;
389
- required = rest.required ? rest.required.length !== 0 : false;
390
- if (!checkParamsSchema(paramsSchema, dynamicParams)) {
391
- throw error2;
392
- }
393
- ref.parameters ??= [];
394
- ref.parameters.push(...toOpenAPIParameters(paramsSchema, "path"));
395
- }
396
- if (method === "GET") {
397
- if (!isObjectSchema(schema)) {
398
- throw new OpenAPIGeneratorError(
399
- 'When method is "GET", input schema must satisfy: object | any | unknown'
400
- );
401
- }
402
- ref.parameters ??= [];
403
- ref.parameters.push(...toOpenAPIParameters(schema, "query"));
404
- } else {
405
- ref.requestBody = {
406
- required,
407
- content: toOpenAPIContent(schema)
408
- };
409
- }
410
- return;
411
- }
412
- const error = new OpenAPIGeneratorError(
413
- 'When input structure is "detailed", input schema must satisfy: { params?: Record<string, unknown>, query?: Record<string, unknown>, headers?: Record<string, unknown>, body?: unknown }'
414
- );
415
- if (!isObjectSchema(schema)) {
416
- throw error;
417
- }
418
- if (dynamicParams?.length && (schema.properties?.params === void 0 || !isObjectSchema(schema.properties.params) || !checkParamsSchema(schema.properties.params, dynamicParams))) {
419
- throw new OpenAPIGeneratorError(
420
- 'When input structure is "detailed" and path has dynamic params, the "params" schema must be an object with all dynamic params as required.'
421
- );
422
- }
423
- for (const from of ["params", "query", "headers"]) {
424
- const fromSchema = schema.properties?.[from];
425
- if (fromSchema !== void 0) {
426
- if (!isObjectSchema(fromSchema)) {
427
- throw error;
428
- }
429
- const parameterIn = from === "params" ? "path" : from === "headers" ? "header" : "query";
430
- ref.parameters ??= [];
431
- ref.parameters.push(...toOpenAPIParameters(fromSchema, parameterIn));
432
- }
433
- }
434
- if (schema.properties?.body !== void 0) {
435
- ref.requestBody = {
436
- required: schema.required?.includes("body"),
437
- content: toOpenAPIContent(schema.properties.body)
438
- };
439
- }
440
- }
441
- async #successResponse(ref, def) {
442
- const outputSchema = def.outputSchema;
443
- const status = fallbackContractConfig("defaultSuccessStatus", def.route.successStatus);
444
- const description = fallbackContractConfig("defaultSuccessDescription", def.route?.successDescription);
445
- const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(outputSchema);
446
- const outputStructure = fallbackContractConfig("defaultOutputStructure", def.route.outputStructure);
447
- if (eventIteratorSchemaDetails) {
448
- ref.responses ??= {};
449
- ref.responses[status] = {
450
- description,
451
- content: toOpenAPIEventIteratorContent(
452
- await this.converter.convert(eventIteratorSchemaDetails.yields, { strategy: "output" }),
453
- await this.converter.convert(eventIteratorSchemaDetails.returns, { strategy: "output" })
454
- )
455
- };
456
- return;
457
- }
458
- const [required, json] = await this.converter.convert(outputSchema, { strategy: "output" });
459
- ref.responses ??= {};
460
- ref.responses[status] = {
461
- description
462
- };
463
- if (outputStructure === "compact") {
464
- ref.responses[status].content = toOpenAPIContent(applySchemaOptionality(required, json));
465
- return;
466
- }
467
- const error = new OpenAPIGeneratorError(
468
- 'When output structure is "detailed", output schema must satisfy: { headers?: Record<string, unknown>, body?: unknown }'
469
- );
470
- if (!isObjectSchema(json)) {
471
- throw error;
472
- }
473
- if (json.properties?.headers !== void 0) {
474
- if (!isObjectSchema(json.properties.headers)) {
475
- throw error;
476
- }
477
- for (const key in json.properties.headers.properties) {
478
- ref.responses[status].headers ??= {};
479
- ref.responses[status].headers[key] = {
480
- schema: toOpenAPISchema(json.properties.headers.properties[key]),
481
- required: json.properties.headers.required?.includes(key)
482
- };
483
- }
484
- }
485
- if (json.properties?.body !== void 0) {
486
- ref.responses[status].content = toOpenAPIContent(
487
- applySchemaOptionality(json.required?.includes("body") ?? false, json.properties.body)
488
- );
489
- }
490
- }
491
- async #errorResponse(ref, def) {
492
- const errorMap = def.errorMap;
493
- const errors = {};
494
- for (const code in errorMap) {
495
- const config = errorMap[code];
496
- if (!config) {
497
- continue;
498
- }
499
- const status = fallbackORPCErrorStatus(code, config.status);
500
- const message = fallbackORPCErrorMessage(code, config.message);
501
- const [dataRequired, dataSchema] = await this.converter.convert(config.data, { strategy: "output" });
502
- errors[status] ??= [];
503
- errors[status].push({
504
- type: "object",
505
- properties: {
506
- defined: { const: true },
507
- code: { const: code },
508
- status: { const: status },
509
- message: { type: "string", default: message },
510
- data: dataSchema
511
- },
512
- required: dataRequired ? ["defined", "code", "status", "message", "data"] : ["defined", "code", "status", "message"]
513
- });
514
- }
515
- ref.responses ??= {};
516
- for (const status in errors) {
517
- const schemas = errors[status];
518
- ref.responses[status] = {
519
- description: status,
520
- content: toOpenAPIContent({
521
- oneOf: [
522
- ...schemas,
523
- {
524
- type: "object",
525
- properties: {
526
- defined: { const: false },
527
- code: { type: "string" },
528
- status: { type: "number" },
529
- message: { type: "string" },
530
- data: {}
531
- },
532
- required: ["defined", "code", "status", "message"]
533
- }
534
- ]
535
- })
536
- };
537
- }
538
- }
539
- }
4
+ import '@orpc/client';
5
+ import '@orpc/client/standard';
6
+ import '@orpc/contract';
7
+ import '@orpc/openapi-client/standard';
8
+ import '@orpc/server';
9
+ import '@orpc/shared';
540
10
 
541
11
  const oo = {
542
12
  spec: customOpenAPIOperation
543
13
  };
544
14
 
545
- export { CompositeSchemaConverter, LOGIC_KEYWORDS, OpenAPIGenerator, applyCustomOpenAPIOperation, applySchemaOptionality, checkParamsSchema, customOpenAPIOperation, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, oo, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
15
+ export { customOpenAPIOperation, oo };