@temporary-name/server 1.9.3-alpha.30822ad82102dcf9276d473ba372416778807e52 → 1.9.3-alpha.32780b2c7ad58cf8dcbc93a40f13494185223e6e

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 (34) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +12 -6
  2. package/dist/adapters/aws-lambda/index.d.ts +12 -6
  3. package/dist/adapters/aws-lambda/index.mjs +12 -4
  4. package/dist/adapters/fetch/index.d.mts +12 -6
  5. package/dist/adapters/fetch/index.d.ts +12 -6
  6. package/dist/adapters/fetch/index.mjs +12 -11
  7. package/dist/adapters/node/index.d.mts +12 -6
  8. package/dist/adapters/node/index.d.ts +12 -6
  9. package/dist/adapters/node/index.mjs +12 -11
  10. package/dist/adapters/standard/index.d.mts +28 -13
  11. package/dist/adapters/standard/index.d.ts +28 -13
  12. package/dist/adapters/standard/index.mjs +8 -100
  13. package/dist/index.d.mts +66 -339
  14. package/dist/index.d.ts +66 -339
  15. package/dist/index.mjs +126 -355
  16. package/dist/openapi/index.d.mts +220 -0
  17. package/dist/openapi/index.d.ts +220 -0
  18. package/dist/openapi/index.mjs +759 -0
  19. package/dist/plugins/index.d.mts +2 -2
  20. package/dist/plugins/index.d.ts +2 -2
  21. package/dist/shared/{server.Btxrgkj5.d.ts → server.BRCH88Sb.d.mts} +7 -24
  22. package/dist/shared/server.Bb9Wxubg.d.ts +23 -0
  23. package/dist/shared/server.BbfNcgas.d.mts +23 -0
  24. package/dist/shared/{server.Bo94xDTv.d.mts → server.D24uJlXJ.d.ts} +7 -24
  25. package/dist/shared/server.DlRH_uit.mjs +409 -0
  26. package/dist/shared/server.Kxw442A9.mjs +247 -0
  27. package/dist/shared/{server.C1YnHvvf.d.ts → server.XpnxYU3D.d.mts} +128 -73
  28. package/dist/shared/{server.C1YnHvvf.d.mts → server.XpnxYU3D.d.ts} +128 -73
  29. package/dist/shared/server.u-02Z0mj.mjs +254 -0
  30. package/package.json +17 -10
  31. package/dist/shared/server.BEQrAa3A.mjs +0 -207
  32. package/dist/shared/server.D6K9uoPI.mjs +0 -35
  33. package/dist/shared/server.DZ5BIITo.mjs +0 -9
  34. package/dist/shared/server.X0YaZxSJ.mjs +0 -13
@@ -0,0 +1,759 @@
1
+ import { isProcedure, resolveContractProcedures, ORPCError, createRouterClient } from '@temporary-name/server';
2
+ import { fallbackContractConfig, getEventIteratorSchemaDetails } from '@temporary-name/contract';
3
+ import { isObject, stringifyJSON, findDeepMatches, toArray, clone, value, toHttpPath, isORPCErrorStatus, fallbackORPCErrorStatus, fallbackORPCErrorMessage, resolveMaybeOptionalOptions, createORPCErrorFromJson } from '@temporary-name/shared';
4
+ import { a as standardizeHTTPPath, j as jsonSerialize, g as getDynamicParams, d as deserialize, s as serialize } from '../shared/server.Kxw442A9.mjs';
5
+ import '@temporary-name/standard-server';
6
+ import { TypeName } from '@temporary-name/interop/json-schema-typed/draft-2020-12';
7
+ export { ContentEncoding as JSONSchemaContentEncoding, Format as JSONSchemaFormat, TypeName as JSONSchemaTypeName } from '@temporary-name/interop/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(
118
+ (k) => !["type", "properties", "required", "additionalProperties"].includes(k) && LOGIC_KEYWORDS.includes(k) && schema[k] !== void 0
119
+ )) {
120
+ return [{ type: "object" }, schema];
121
+ }
122
+ const matched = { ...schema };
123
+ const rest = { ...schema };
124
+ matched.properties = separatedProperties.reduce((acc, key) => {
125
+ const keySchema = schema.properties?.[key] ?? schema.additionalProperties;
126
+ if (keySchema !== void 0) {
127
+ acc[key] = keySchema;
128
+ }
129
+ return acc;
130
+ }, {});
131
+ matched.required = schema.required?.filter((key) => separatedProperties.includes(key));
132
+ matched.examples = schema.examples?.map((example) => {
133
+ if (!isObject(example)) {
134
+ return example;
135
+ }
136
+ return Object.entries(example).reduce(
137
+ (acc, [key, value]) => {
138
+ if (separatedProperties.includes(key)) {
139
+ acc[key] = value;
140
+ }
141
+ return acc;
142
+ },
143
+ {}
144
+ );
145
+ });
146
+ rest.properties = schema.properties && Object.entries(schema.properties).filter(([key]) => !separatedProperties.includes(key)).reduce(
147
+ (acc, [key, value]) => {
148
+ acc[key] = value;
149
+ return acc;
150
+ },
151
+ {}
152
+ );
153
+ rest.required = schema.required?.filter((key) => !separatedProperties.includes(key));
154
+ rest.examples = schema.examples?.map((example) => {
155
+ if (!isObject(example)) {
156
+ return example;
157
+ }
158
+ return Object.entries(example).reduce(
159
+ (acc, [key, value]) => {
160
+ if (!separatedProperties.includes(key)) {
161
+ acc[key] = value;
162
+ }
163
+ return acc;
164
+ },
165
+ {}
166
+ );
167
+ });
168
+ return [matched, rest];
169
+ }
170
+ function filterSchemaBranches(schema, check, matches = []) {
171
+ if (check(schema)) {
172
+ matches.push(schema);
173
+ return [matches, void 0];
174
+ }
175
+ if (isObject(schema)) {
176
+ for (const keyword of ["anyOf", "oneOf"]) {
177
+ if (schema[keyword] && Object.keys(schema).every((k) => k === keyword || !LOGIC_KEYWORDS.includes(k))) {
178
+ const rest = schema[keyword].map((s) => filterSchemaBranches(s, check, matches)[1]).filter((v) => !!v);
179
+ if (rest.length === 1 && typeof rest[0] === "object") {
180
+ return [matches, { ...schema, [keyword]: void 0, ...rest[0] }];
181
+ }
182
+ return [matches, { ...schema, [keyword]: rest }];
183
+ }
184
+ }
185
+ }
186
+ return [matches, schema];
187
+ }
188
+ function applySchemaOptionality(required, schema) {
189
+ if (required) {
190
+ return schema;
191
+ }
192
+ return {
193
+ anyOf: [schema, { not: {} }]
194
+ };
195
+ }
196
+ function expandUnionSchema(schema) {
197
+ if (typeof schema === "object") {
198
+ for (const keyword of ["anyOf", "oneOf"]) {
199
+ if (schema[keyword] && Object.keys(schema).every((k) => k === keyword || !LOGIC_KEYWORDS.includes(k))) {
200
+ return schema[keyword].flatMap((s) => expandUnionSchema(s));
201
+ }
202
+ }
203
+ }
204
+ return [schema];
205
+ }
206
+ function expandArrayableSchema(schema) {
207
+ const schemas = expandUnionSchema(schema);
208
+ if (schemas.length !== 2) {
209
+ return void 0;
210
+ }
211
+ const arraySchema = schemas.find(
212
+ (s) => typeof s === "object" && s.type === "array" && Object.keys(s).filter((k) => LOGIC_KEYWORDS.includes(k)).every((k) => k === "type" || k === "items")
213
+ );
214
+ if (arraySchema === void 0) {
215
+ return void 0;
216
+ }
217
+ const items1 = arraySchema.items;
218
+ const items2 = schemas.find((s) => s !== arraySchema);
219
+ if (stringifyJSON(items1) !== stringifyJSON(items2)) {
220
+ return void 0;
221
+ }
222
+ return [items2, arraySchema];
223
+ }
224
+ const PRIMITIVE_SCHEMA_TYPES = /* @__PURE__ */ new Set([
225
+ TypeName.String,
226
+ TypeName.Number,
227
+ TypeName.Integer,
228
+ TypeName.Boolean,
229
+ TypeName.Null
230
+ ]);
231
+ function isPrimitiveSchema(schema) {
232
+ return expandUnionSchema(schema).every((s) => {
233
+ if (typeof s === "boolean") {
234
+ return false;
235
+ }
236
+ if (typeof s.type === "string" && PRIMITIVE_SCHEMA_TYPES.has(s.type)) {
237
+ return true;
238
+ }
239
+ if (s.const !== void 0) {
240
+ return true;
241
+ }
242
+ return false;
243
+ });
244
+ }
245
+
246
+ function toOpenAPIPath(path) {
247
+ return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/{$1}");
248
+ }
249
+ function toOpenAPIMethod(method) {
250
+ return method.toLocaleLowerCase();
251
+ }
252
+ function toOpenAPIContent(schema) {
253
+ const content = {};
254
+ const [matches, restSchema] = filterSchemaBranches(schema, isFileSchema);
255
+ for (const file of matches) {
256
+ content[file.contentMediaType] = {
257
+ schema: toOpenAPISchema(file)
258
+ };
259
+ }
260
+ if (restSchema !== void 0) {
261
+ content["application/json"] = {
262
+ schema: toOpenAPISchema(restSchema)
263
+ };
264
+ const isStillHasFileSchema = findDeepMatches((v) => isObject(v) && isFileSchema(v), restSchema).values.length > 0;
265
+ if (isStillHasFileSchema) {
266
+ content["multipart/form-data"] = {
267
+ schema: toOpenAPISchema(restSchema)
268
+ };
269
+ }
270
+ }
271
+ return content;
272
+ }
273
+ function toOpenAPIEventIteratorContent([yieldsRequired, yieldsSchema], [returnsRequired, returnsSchema]) {
274
+ return {
275
+ "text/event-stream": {
276
+ schema: toOpenAPISchema({
277
+ oneOf: [
278
+ {
279
+ type: "object",
280
+ properties: {
281
+ event: { const: "message" },
282
+ data: yieldsSchema,
283
+ id: { type: "string" },
284
+ retry: { type: "number" }
285
+ },
286
+ required: yieldsRequired ? ["event", "data"] : ["event"]
287
+ },
288
+ {
289
+ type: "object",
290
+ properties: {
291
+ event: { const: "done" },
292
+ data: returnsSchema,
293
+ id: { type: "string" },
294
+ retry: { type: "number" }
295
+ },
296
+ required: returnsRequired ? ["event", "data"] : ["event"]
297
+ },
298
+ {
299
+ type: "object",
300
+ properties: {
301
+ event: { const: "error" },
302
+ data: {},
303
+ id: { type: "string" },
304
+ retry: { type: "number" }
305
+ },
306
+ required: ["event"]
307
+ }
308
+ ]
309
+ })
310
+ }
311
+ };
312
+ }
313
+ function toOpenAPIParameters(schema, parameterIn) {
314
+ const parameters = [];
315
+ for (const key in schema.properties) {
316
+ const keySchema = schema.properties[key];
317
+ let isDeepObjectStyle = true;
318
+ if (parameterIn !== "query") {
319
+ isDeepObjectStyle = false;
320
+ } else if (isPrimitiveSchema(keySchema)) {
321
+ isDeepObjectStyle = false;
322
+ } else {
323
+ const [item] = expandArrayableSchema(keySchema) ?? [];
324
+ if (item !== void 0 && isPrimitiveSchema(item)) {
325
+ isDeepObjectStyle = false;
326
+ }
327
+ }
328
+ parameters.push({
329
+ name: key,
330
+ in: parameterIn,
331
+ required: schema.required?.includes(key),
332
+ schema: toOpenAPISchema(keySchema),
333
+ style: isDeepObjectStyle ? "deepObject" : void 0,
334
+ explode: isDeepObjectStyle ? true : void 0,
335
+ allowEmptyValue: parameterIn === "query" ? true : void 0,
336
+ allowReserved: parameterIn === "query" ? true : void 0
337
+ });
338
+ }
339
+ return parameters;
340
+ }
341
+ function checkParamsSchema(schema, params) {
342
+ const properties = Object.keys(schema.properties ?? {});
343
+ const required = schema.required ?? [];
344
+ if (properties.length !== params.length || properties.some((v) => !params.includes(v))) {
345
+ return false;
346
+ }
347
+ if (required.length !== params.length || required.some((v) => !params.includes(v))) {
348
+ return false;
349
+ }
350
+ return true;
351
+ }
352
+ function toOpenAPISchema(schema) {
353
+ return schema === true ? {} : schema === false ? { not: {} } : schema;
354
+ }
355
+ const OPENAPI_JSON_SCHEMA_REF_PREFIX = "#/components/schemas/";
356
+ function resolveOpenAPIJsonSchemaRef(doc, schema) {
357
+ if (typeof schema !== "object" || !schema.$ref?.startsWith(OPENAPI_JSON_SCHEMA_REF_PREFIX)) {
358
+ return schema;
359
+ }
360
+ const name = schema.$ref.slice(OPENAPI_JSON_SCHEMA_REF_PREFIX.length);
361
+ const resolved = doc.components?.schemas?.[name];
362
+ return resolved ?? schema;
363
+ }
364
+
365
+ class CompositeSchemaConverter {
366
+ converters;
367
+ constructor(converters) {
368
+ this.converters = converters;
369
+ }
370
+ async convert(schema, options) {
371
+ for (const converter of this.converters) {
372
+ if (await converter.condition(schema, options)) {
373
+ return converter.convert(schema, options);
374
+ }
375
+ }
376
+ return [false, {}];
377
+ }
378
+ }
379
+
380
+ class OpenAPIGeneratorError extends Error {
381
+ }
382
+ class OpenAPIGenerator {
383
+ converter;
384
+ constructor(options = {}) {
385
+ this.converter = new CompositeSchemaConverter(toArray(options.schemaConverters));
386
+ }
387
+ /**
388
+ * Generates OpenAPI specifications from oRPC routers/contracts.
389
+ *
390
+ * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
391
+ */
392
+ async generate(router, options = {}) {
393
+ const filter = options.filter ?? (({ contract, path }) => {
394
+ return !(options.exclude?.(contract, path) ?? false);
395
+ });
396
+ const doc = {
397
+ ...clone(options),
398
+ info: options.info ?? { title: "API Reference", version: "0.0.0" },
399
+ openapi: "3.1.1",
400
+ exclude: void 0,
401
+ filter: void 0,
402
+ commonSchemas: void 0
403
+ };
404
+ const { baseSchemaConvertOptions, undefinedErrorJsonSchema } = await this.#resolveCommonSchemas(
405
+ doc,
406
+ options.commonSchemas
407
+ );
408
+ const contracts = [];
409
+ await resolveContractProcedures({ path: [], router }, (traverseOptions) => {
410
+ if (!value(filter, traverseOptions)) {
411
+ return;
412
+ }
413
+ contracts.push(traverseOptions);
414
+ });
415
+ const errors = [];
416
+ for (const { contract, path } of contracts) {
417
+ const stringPath = path.join(".");
418
+ try {
419
+ const def = contract["~orpc"];
420
+ const method = toOpenAPIMethod(fallbackContractConfig("defaultMethod", def.route.method));
421
+ const httpPath = toOpenAPIPath(def.route.path ?? toHttpPath(path));
422
+ let operationObjectRef;
423
+ if (def.route.spec !== void 0 && typeof def.route.spec !== "function") {
424
+ operationObjectRef = def.route.spec;
425
+ } else {
426
+ operationObjectRef = {
427
+ operationId: def.route.operationId ?? stringPath,
428
+ summary: def.route.summary,
429
+ description: def.route.description,
430
+ deprecated: def.route.deprecated,
431
+ tags: def.route.tags?.map((tag) => tag)
432
+ };
433
+ await this.#request(doc, operationObjectRef, def, baseSchemaConvertOptions);
434
+ await this.#successResponse(doc, operationObjectRef, def, baseSchemaConvertOptions);
435
+ await this.#errorResponse(
436
+ operationObjectRef,
437
+ def,
438
+ baseSchemaConvertOptions,
439
+ undefinedErrorJsonSchema
440
+ );
441
+ }
442
+ if (typeof def.route.spec === "function") {
443
+ operationObjectRef = def.route.spec(operationObjectRef);
444
+ }
445
+ doc.paths ??= {};
446
+ doc.paths[httpPath] ??= {};
447
+ doc.paths[httpPath][method] = applyCustomOpenAPIOperation(operationObjectRef, contract);
448
+ } catch (e) {
449
+ if (!(e instanceof OpenAPIGeneratorError)) {
450
+ throw e;
451
+ }
452
+ errors.push(
453
+ `[OpenAPIGenerator] Error occurred while generating OpenAPI for procedure at path: ${stringPath}
454
+ ${e.message}`
455
+ );
456
+ }
457
+ }
458
+ if (errors.length) {
459
+ throw new OpenAPIGeneratorError(
460
+ `Some error occurred during OpenAPI generation:
461
+
462
+ ${errors.join("\n\n")}`
463
+ );
464
+ }
465
+ return jsonSerialize(doc)[0];
466
+ }
467
+ async #resolveCommonSchemas(doc, commonSchemas) {
468
+ let undefinedErrorJsonSchema = {
469
+ type: "object",
470
+ properties: {
471
+ defined: { const: false },
472
+ code: { type: "string" },
473
+ status: { type: "number" },
474
+ message: { type: "string" },
475
+ data: {}
476
+ },
477
+ required: ["defined", "code", "status", "message"]
478
+ };
479
+ const baseSchemaConvertOptions = {};
480
+ if (commonSchemas) {
481
+ baseSchemaConvertOptions.components = [];
482
+ for (const key in commonSchemas) {
483
+ const options = commonSchemas[key];
484
+ if (options.schema === void 0) {
485
+ continue;
486
+ }
487
+ const { schema, strategy = "input" } = options;
488
+ const [required, json] = await this.converter.convert(schema, { strategy });
489
+ const allowedStrategies = [strategy];
490
+ if (strategy === "input") {
491
+ const [outputRequired, outputJson] = await this.converter.convert(schema, { strategy: "output" });
492
+ if (outputRequired === required && stringifyJSON(outputJson) === stringifyJSON(json)) {
493
+ allowedStrategies.push("output");
494
+ }
495
+ } else if (strategy === "output") {
496
+ const [inputRequired, inputJson] = await this.converter.convert(schema, { strategy: "input" });
497
+ if (inputRequired === required && stringifyJSON(inputJson) === stringifyJSON(json)) {
498
+ allowedStrategies.push("input");
499
+ }
500
+ }
501
+ baseSchemaConvertOptions.components.push({
502
+ schema,
503
+ required,
504
+ ref: `#/components/schemas/${key}`,
505
+ allowedStrategies
506
+ });
507
+ }
508
+ doc.components ??= {};
509
+ doc.components.schemas ??= {};
510
+ for (const key in commonSchemas) {
511
+ const options = commonSchemas[key];
512
+ if (options.schema === void 0) {
513
+ if (options.error === "UndefinedError") {
514
+ doc.components.schemas[key] = toOpenAPISchema(undefinedErrorJsonSchema);
515
+ undefinedErrorJsonSchema = { $ref: `#/components/schemas/${key}` };
516
+ }
517
+ continue;
518
+ }
519
+ const { schema, strategy = "input" } = options;
520
+ const [, json] = await this.converter.convert(schema, {
521
+ ...baseSchemaConvertOptions,
522
+ strategy,
523
+ minStructureDepthForRef: 1
524
+ // not allow use $ref for root schemas
525
+ });
526
+ doc.components.schemas[key] = toOpenAPISchema(json);
527
+ }
528
+ }
529
+ return { baseSchemaConvertOptions, undefinedErrorJsonSchema };
530
+ }
531
+ async #request(doc, ref, def, baseSchemaConvertOptions) {
532
+ const method = fallbackContractConfig("defaultMethod", def.route.method);
533
+ const dynamicParams = getDynamicParams(def.route.path)?.map((v) => v.name);
534
+ const [_pathRequired, pathSchema] = await this.converter.convert(def.schemas.pathSchema, {
535
+ ...baseSchemaConvertOptions,
536
+ strategy: "input",
537
+ minStructureDepthForRef: 1
538
+ });
539
+ if (dynamicParams?.length) {
540
+ const error = new OpenAPIGeneratorError(
541
+ // TODO: fix this error
542
+ 'When input structure is "compact", and path has dynamic params, input schema must be an object with all dynamic params as required.'
543
+ );
544
+ if (!isObjectSchema(pathSchema)) {
545
+ throw error;
546
+ }
547
+ if (!checkParamsSchema(pathSchema, dynamicParams)) {
548
+ throw error;
549
+ }
550
+ ref.parameters ??= [];
551
+ ref.parameters.push(...toOpenAPIParameters(pathSchema, "path"));
552
+ } else {
553
+ const error = new OpenAPIGeneratorError("Params set via path do not match those on the route");
554
+ if (!isObjectSchema(pathSchema)) {
555
+ console.log("FOO", pathSchema);
556
+ throw error;
557
+ }
558
+ if (!checkParamsSchema(pathSchema, [])) {
559
+ console.log("BAR", pathSchema);
560
+ throw error;
561
+ }
562
+ }
563
+ const [_queryRequired, querySchema] = await this.converter.convert(def.schemas.querySchema, {
564
+ ...baseSchemaConvertOptions,
565
+ strategy: "input",
566
+ minStructureDepthForRef: 0
567
+ });
568
+ if (!isAnySchema(querySchema)) {
569
+ const resolvedSchema = resolveOpenAPIJsonSchemaRef(doc, querySchema);
570
+ if (!isObjectSchema(resolvedSchema)) {
571
+ throw new OpenAPIGeneratorError("Query param schema must satisfy: object | any | unknown");
572
+ }
573
+ ref.parameters ??= [];
574
+ ref.parameters.push(...toOpenAPIParameters(resolvedSchema, "query"));
575
+ }
576
+ if (method !== "GET") {
577
+ const details = getEventIteratorSchemaDetails(def.schemas.bodySchema);
578
+ if (details) {
579
+ ref.requestBody = {
580
+ required: true,
581
+ content: toOpenAPIEventIteratorContent(
582
+ await this.converter.convert(details.yields, { ...baseSchemaConvertOptions, strategy: "input" }),
583
+ await this.converter.convert(details.returns, { ...baseSchemaConvertOptions, strategy: "input" })
584
+ )
585
+ };
586
+ } else {
587
+ const [bodyRequired, bodySchema] = await this.converter.convert(def.schemas.bodySchema, {
588
+ ...baseSchemaConvertOptions,
589
+ strategy: "input",
590
+ minStructureDepthForRef: 0
591
+ });
592
+ if (isAnySchema(bodySchema)) {
593
+ return;
594
+ }
595
+ ref.requestBody = {
596
+ required: bodyRequired,
597
+ content: toOpenAPIContent(bodySchema)
598
+ };
599
+ }
600
+ }
601
+ }
602
+ async #successResponse(doc, ref, def, baseSchemaConvertOptions) {
603
+ const outputSchema = def.schemas.outputSchema;
604
+ const status = fallbackContractConfig("defaultSuccessStatus", def.route.successStatus);
605
+ const description = fallbackContractConfig("defaultSuccessDescription", def.route?.successDescription);
606
+ const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(outputSchema);
607
+ const outputStructure = fallbackContractConfig("defaultOutputStructure", def.route.outputStructure);
608
+ if (eventIteratorSchemaDetails) {
609
+ ref.responses ??= {};
610
+ ref.responses[status] = {
611
+ description,
612
+ content: toOpenAPIEventIteratorContent(
613
+ await this.converter.convert(eventIteratorSchemaDetails.yields, {
614
+ ...baseSchemaConvertOptions,
615
+ strategy: "output"
616
+ }),
617
+ await this.converter.convert(eventIteratorSchemaDetails.returns, {
618
+ ...baseSchemaConvertOptions,
619
+ strategy: "output"
620
+ })
621
+ )
622
+ };
623
+ return;
624
+ }
625
+ const [required, json] = await this.converter.convert(outputSchema, {
626
+ ...baseSchemaConvertOptions,
627
+ strategy: "output",
628
+ minStructureDepthForRef: outputStructure === "detailed" ? 1 : 0
629
+ });
630
+ if (outputStructure === "compact") {
631
+ ref.responses ??= {};
632
+ ref.responses[status] = {
633
+ description
634
+ };
635
+ ref.responses[status].content = toOpenAPIContent(applySchemaOptionality(required, json));
636
+ return;
637
+ }
638
+ const handledStatuses = /* @__PURE__ */ new Set();
639
+ for (const item of expandUnionSchema(json)) {
640
+ const error = new OpenAPIGeneratorError(`
641
+ When output structure is "detailed", output schema must satisfy:
642
+ {
643
+ status?: number, // must be a literal number and in the range of 200-399
644
+ headers?: Record<string, unknown>,
645
+ body?: unknown
646
+ }
647
+
648
+ But got: ${stringifyJSON(item)}
649
+ `);
650
+ if (!isObjectSchema(item)) {
651
+ throw error;
652
+ }
653
+ let schemaStatus;
654
+ let schemaDescription;
655
+ if (item.properties?.status !== void 0) {
656
+ const statusSchema = resolveOpenAPIJsonSchemaRef(doc, item.properties.status);
657
+ if (typeof statusSchema !== "object" || statusSchema.const === void 0 || typeof statusSchema.const !== "number" || !Number.isInteger(statusSchema.const) || isORPCErrorStatus(statusSchema.const)) {
658
+ throw error;
659
+ }
660
+ schemaStatus = statusSchema.const;
661
+ schemaDescription = statusSchema.description;
662
+ }
663
+ const itemStatus = schemaStatus ?? status;
664
+ const itemDescription = schemaDescription ?? description;
665
+ if (handledStatuses.has(itemStatus)) {
666
+ throw new OpenAPIGeneratorError(`
667
+ When output structure is "detailed", each success status must be unique.
668
+ But got status: ${itemStatus} used more than once.
669
+ `);
670
+ }
671
+ handledStatuses.add(itemStatus);
672
+ ref.responses ??= {};
673
+ ref.responses[itemStatus] = {
674
+ description: itemDescription
675
+ };
676
+ if (item.properties?.headers !== void 0) {
677
+ const headersSchema = resolveOpenAPIJsonSchemaRef(doc, item.properties.headers);
678
+ if (!isObjectSchema(headersSchema)) {
679
+ throw error;
680
+ }
681
+ for (const key in headersSchema.properties) {
682
+ const headerSchema = headersSchema.properties[key];
683
+ if (headerSchema !== void 0) {
684
+ ref.responses[itemStatus].headers ??= {};
685
+ ref.responses[itemStatus].headers[key] = {
686
+ schema: toOpenAPISchema(headerSchema),
687
+ required: item.required?.includes("headers") && headersSchema.required?.includes(key)
688
+ };
689
+ }
690
+ }
691
+ }
692
+ if (item.properties?.body !== void 0) {
693
+ ref.responses[itemStatus].content = toOpenAPIContent(
694
+ applySchemaOptionality(item.required?.includes("body") ?? false, item.properties.body)
695
+ );
696
+ }
697
+ }
698
+ }
699
+ async #errorResponse(ref, def, baseSchemaConvertOptions, undefinedErrorSchema) {
700
+ const errorMap = def.errorMap;
701
+ const errors = {};
702
+ for (const code in errorMap) {
703
+ const config = errorMap[code];
704
+ if (!config) {
705
+ continue;
706
+ }
707
+ const status = fallbackORPCErrorStatus(code, config.status);
708
+ const message = fallbackORPCErrorMessage(code, config.message);
709
+ const [dataRequired, dataSchema] = await this.converter.convert(config.data, {
710
+ ...baseSchemaConvertOptions,
711
+ strategy: "output"
712
+ });
713
+ errors[status] ??= [];
714
+ errors[status].push({
715
+ type: "object",
716
+ properties: {
717
+ defined: { const: true },
718
+ code: { const: code },
719
+ status: { const: status },
720
+ message: { type: "string", default: message },
721
+ data: dataSchema
722
+ },
723
+ required: dataRequired ? ["defined", "code", "status", "message", "data"] : ["defined", "code", "status", "message"]
724
+ });
725
+ }
726
+ ref.responses ??= {};
727
+ for (const status in errors) {
728
+ const schemas = errors[status];
729
+ ref.responses[status] = {
730
+ description: status,
731
+ content: toOpenAPIContent({
732
+ oneOf: [...schemas, undefinedErrorSchema]
733
+ })
734
+ };
735
+ }
736
+ }
737
+ }
738
+
739
+ function createJsonifiedRouterClient(router, ...rest) {
740
+ const options = resolveMaybeOptionalOptions(rest);
741
+ options.interceptors ??= [];
742
+ options.interceptors.unshift(async (options2) => {
743
+ try {
744
+ return deserialize(serialize(await options2.next()));
745
+ } catch (e) {
746
+ if (e instanceof ORPCError) {
747
+ throw createORPCErrorFromJson(deserialize(serialize(e.toJSON(), { outputFormat: "plain" })));
748
+ }
749
+ throw e;
750
+ }
751
+ });
752
+ return createRouterClient(router, options);
753
+ }
754
+
755
+ const oo = {
756
+ spec: customOpenAPIOperation
757
+ };
758
+
759
+ export { CompositeSchemaConverter, LOGIC_KEYWORDS, OpenAPIGenerator, applyCustomOpenAPIOperation, applySchemaOptionality, checkParamsSchema, createJsonifiedRouterClient, customOpenAPIOperation, expandArrayableSchema, expandUnionSchema, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, isPrimitiveSchema, oo, resolveOpenAPIJsonSchemaRef, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };