@orpc/openapi 0.0.0-next.9cd157a → 0.0.0-next.9cd4eb7

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.
@@ -1,5 +1,5 @@
1
- import { stringifyJSON, value } from '@orpc/shared';
2
- import { O as OpenAPIGenerator } from '../shared/openapi.fMEQd3Yd.mjs';
1
+ import { stringifyJSON, once, value } from '@orpc/shared';
2
+ import { O as OpenAPIGenerator } from '../shared/openapi.DrrBsJ0w.mjs';
3
3
  import '@orpc/client';
4
4
  import '@orpc/client/standard';
5
5
  import '@orpc/contract';
@@ -27,25 +27,32 @@ class OpenAPIReferencePlugin {
27
27
  this.specPath = options.specPath ?? "/spec.json";
28
28
  this.generator = new OpenAPIGenerator(options);
29
29
  const esc = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
30
- this.renderDocsHtml = options.renderDocsHtml ?? ((specUrl, title, head, scriptUrl, config) => `
31
- <!doctype html>
32
- <html>
33
- <head>
34
- <meta charset="utf-8" />
35
- <meta name="viewport" content="width=device-width, initial-scale=1" />
36
- <title>${esc(title)}</title>
37
- ${head}
38
- </head>
39
- <body>
40
- <script
41
- id="api-reference"
42
- data-url="${esc(specUrl)}"
43
- ${config !== void 0 ? `data-configuration="${esc(stringifyJSON(config))}"` : ""}
44
- ><\/script>
45
- <script src="${esc(scriptUrl)}"><\/script>
46
- </body>
47
- </html>
48
- `);
30
+ this.renderDocsHtml = options.renderDocsHtml ?? ((specUrl, title, head, scriptUrl, config, spec) => {
31
+ const finalConfig = {
32
+ content: stringifyJSON(spec),
33
+ ...config
34
+ };
35
+ return `
36
+ <!doctype html>
37
+ <html>
38
+ <head>
39
+ <meta charset="utf-8" />
40
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
41
+ <title>${esc(title)}</title>
42
+ ${head}
43
+ </head>
44
+ <body>
45
+ <div id="app" data-config="${esc(stringifyJSON(finalConfig))}"></div>
46
+
47
+ <script src="${esc(scriptUrl)}"><\/script>
48
+
49
+ <script>
50
+ Scalar.createApiReference('#app', JSON.parse(document.getElementById('app').dataset.config))
51
+ <\/script>
52
+ </body>
53
+ </html>
54
+ `;
55
+ });
49
56
  }
50
57
  init(options, router) {
51
58
  options.interceptors ??= [];
@@ -58,11 +65,14 @@ class OpenAPIReferencePlugin {
58
65
  const requestPathname = options2.request.url.pathname.replace(/\/$/, "") || "/";
59
66
  const docsUrl = new URL(`${prefix}${this.docsPath}`.replace(/\/$/, ""), options2.request.url.origin);
60
67
  const specUrl = new URL(`${prefix}${this.specPath}`.replace(/\/$/, ""), options2.request.url.origin);
61
- if (requestPathname === specUrl.pathname) {
62
- const spec = await this.generator.generate(router, {
68
+ const generateSpec = once(async () => {
69
+ return await this.generator.generate(router, {
63
70
  servers: [{ url: new URL(prefix, options2.request.url.origin).toString() }],
64
71
  ...await value(this.specGenerateOptions, options2)
65
72
  });
73
+ });
74
+ if (requestPathname === specUrl.pathname) {
75
+ const spec = await generateSpec();
66
76
  return {
67
77
  matched: true,
68
78
  response: {
@@ -78,7 +88,8 @@ class OpenAPIReferencePlugin {
78
88
  await value(this.docsTitle, options2),
79
89
  await value(this.docsHead, options2),
80
90
  await value(this.docsScriptUrl, options2),
81
- await value(this.docsConfig, options2)
91
+ await value(this.docsConfig, options2),
92
+ await generateSpec()
82
93
  );
83
94
  return {
84
95
  matched: true,
@@ -1,7 +1,8 @@
1
1
  import { standardizeHTTPPath, StandardOpenAPIJsonSerializer, StandardBracketNotationSerializer, StandardOpenAPISerializer } from '@orpc/openapi-client/standard';
2
2
  import { StandardHandler } from '@orpc/server/standard';
3
+ import { isORPCErrorStatus } from '@orpc/client';
3
4
  import { fallbackContractConfig } from '@orpc/contract';
4
- import { isObject } from '@orpc/shared';
5
+ import { isObject, stringifyJSON } from '@orpc/shared';
5
6
  import { toHttpPath } from '@orpc/client/standard';
6
7
  import { traverseContractProcedures, isProcedure, getLazyMeta, unlazy, getRouter, createContractedProcedure } from '@orpc/server';
7
8
  import { createRouter, addRoute, findRoute } from 'rou3';
@@ -52,13 +53,21 @@ class StandardOpenAPICodec {
52
53
  body: this.serializer.serialize(output)
53
54
  };
54
55
  }
55
- if (!isObject(output)) {
56
- throw new Error(
57
- 'Invalid output structure for "detailed" output. Expected format: { body: any, headers?: Record<string, string | string[] | undefined> }'
58
- );
56
+ if (!this.#isDetailedOutput(output)) {
57
+ throw new Error(`
58
+ Invalid "detailed" output structure:
59
+ \u2022 Expected an object with optional properties:
60
+ - status (number 200-399)
61
+ - headers (Record<string, string | string[]>)
62
+ - body (any)
63
+ \u2022 No extra keys allowed.
64
+
65
+ Actual value:
66
+ ${stringifyJSON(output)}
67
+ `);
59
68
  }
60
69
  return {
61
- status: successStatus,
70
+ status: output.status ?? successStatus,
62
71
  headers: output.headers ?? {},
63
72
  body: this.serializer.serialize(output.body)
64
73
  };
@@ -70,6 +79,18 @@ class StandardOpenAPICodec {
70
79
  body: this.serializer.serialize(error.toJSON(), { outputFormat: "plain" })
71
80
  };
72
81
  }
82
+ #isDetailedOutput(output) {
83
+ if (!isObject(output)) {
84
+ return false;
85
+ }
86
+ if (output.headers && !isObject(output.headers)) {
87
+ return false;
88
+ }
89
+ if (output.status !== void 0 && (typeof output.status !== "number" || !Number.isInteger(output.status) || isORPCErrorStatus(output.status))) {
90
+ return false;
91
+ }
92
+ return true;
93
+ }
73
94
  }
74
95
 
75
96
  function toRou3Pattern(path) {
@@ -147,7 +168,7 @@ class StandardOpenAPIMatcher {
147
168
  class StandardOpenAPIHandler extends StandardHandler {
148
169
  constructor(router, options) {
149
170
  const jsonSerializer = new StandardOpenAPIJsonSerializer(options);
150
- const bracketNotationSerializer = new StandardBracketNotationSerializer();
171
+ const bracketNotationSerializer = new StandardBracketNotationSerializer(options);
151
172
  const serializer = new StandardOpenAPISerializer(jsonSerializer, bracketNotationSerializer);
152
173
  const matcher = new StandardOpenAPIMatcher();
153
174
  const codec = new StandardOpenAPICodec(serializer);
@@ -0,0 +1,101 @@
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 SchemaConverterComponent {
8
+ allowedStrategies: readonly SchemaConvertOptions['strategy'][];
9
+ schema: AnySchema;
10
+ required: boolean;
11
+ ref: string;
12
+ }
13
+ interface SchemaConvertOptions {
14
+ strategy: 'input' | 'output';
15
+ /**
16
+ * Common components should use `$ref` to represent themselves if matched.
17
+ */
18
+ components?: readonly SchemaConverterComponent[];
19
+ /**
20
+ * Minimum schema structure depth required before using `$ref` for components.
21
+ *
22
+ * For example, if set to 2, `$ref` will only be used for schemas nested at depth 2 or greater.
23
+ *
24
+ * @default 0 - No depth limit;
25
+ */
26
+ minStructureDepthForRef?: number;
27
+ }
28
+ interface SchemaConverter {
29
+ convert(schema: AnySchema | undefined, options: SchemaConvertOptions): Promisable<[required: boolean, jsonSchema: JSONSchema]>;
30
+ }
31
+ interface ConditionalSchemaConverter extends SchemaConverter {
32
+ condition(schema: AnySchema | undefined, options: SchemaConvertOptions): Promisable<boolean>;
33
+ }
34
+ declare class CompositeSchemaConverter implements SchemaConverter {
35
+ private readonly converters;
36
+ constructor(converters: readonly ConditionalSchemaConverter[]);
37
+ convert(schema: AnySchema | undefined, options: SchemaConvertOptions): Promise<[required: boolean, jsonSchema: JSONSchema]>;
38
+ }
39
+
40
+ interface OpenAPIGeneratorOptions extends StandardOpenAPIJsonSerializerOptions {
41
+ schemaConverters?: ConditionalSchemaConverter[];
42
+ }
43
+ interface OpenAPIGeneratorGenerateOptions extends Partial<Omit<OpenAPI.Document, 'openapi'>> {
44
+ /**
45
+ * Exclude procedures from the OpenAPI specification.
46
+ *
47
+ * @default () => false
48
+ */
49
+ exclude?: (procedure: AnyProcedure | AnyContractProcedure, path: readonly string[]) => boolean;
50
+ /**
51
+ * Common schemas to be used for $ref resolution.
52
+ */
53
+ commonSchemas?: Record<string, {
54
+ /**
55
+ * Determines which schema definition to use when input and output schemas differ.
56
+ * This is needed because some schemas transform data differently between input and output,
57
+ * making it impossible to use a single $ref for both cases.
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * // This schema transforms a string input into a number output
62
+ * const Schema = z.string()
63
+ * .transform(v => Number(v))
64
+ * .pipe(z.number())
65
+ *
66
+ * // Input schema: { type: 'string' }
67
+ * // Output schema: { type: 'number' }
68
+ * ```
69
+ *
70
+ * When schemas differ between input and output, you must explicitly choose
71
+ * which version to use for the OpenAPI specification.
72
+ *
73
+ * @default 'input' - Uses the input schema definition by default
74
+ */
75
+ strategy?: SchemaConvertOptions['strategy'];
76
+ schema: AnySchema;
77
+ } | {
78
+ error: 'UndefinedError';
79
+ schema?: never;
80
+ }>;
81
+ }
82
+ /**
83
+ * The generator that converts oRPC routers/contracts to OpenAPI specifications.
84
+ *
85
+ * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
86
+ */
87
+ declare class OpenAPIGenerator {
88
+ #private;
89
+ private readonly serializer;
90
+ private readonly converter;
91
+ constructor(options?: OpenAPIGeneratorOptions);
92
+ /**
93
+ * Generates OpenAPI specifications from oRPC routers/contracts.
94
+ *
95
+ * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
96
+ */
97
+ generate(router: AnyContractRouter | AnyRouter, options?: OpenAPIGeneratorGenerateOptions): Promise<OpenAPI.Document>;
98
+ }
99
+
100
+ export { OpenAPIGenerator as b, CompositeSchemaConverter as e };
101
+ export type { ConditionalSchemaConverter as C, OpenAPIGeneratorOptions as O, SchemaConverterComponent as S, OpenAPIGeneratorGenerateOptions as a, SchemaConvertOptions as c, SchemaConverter as d };
@@ -0,0 +1,101 @@
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 SchemaConverterComponent {
8
+ allowedStrategies: readonly SchemaConvertOptions['strategy'][];
9
+ schema: AnySchema;
10
+ required: boolean;
11
+ ref: string;
12
+ }
13
+ interface SchemaConvertOptions {
14
+ strategy: 'input' | 'output';
15
+ /**
16
+ * Common components should use `$ref` to represent themselves if matched.
17
+ */
18
+ components?: readonly SchemaConverterComponent[];
19
+ /**
20
+ * Minimum schema structure depth required before using `$ref` for components.
21
+ *
22
+ * For example, if set to 2, `$ref` will only be used for schemas nested at depth 2 or greater.
23
+ *
24
+ * @default 0 - No depth limit;
25
+ */
26
+ minStructureDepthForRef?: number;
27
+ }
28
+ interface SchemaConverter {
29
+ convert(schema: AnySchema | undefined, options: SchemaConvertOptions): Promisable<[required: boolean, jsonSchema: JSONSchema]>;
30
+ }
31
+ interface ConditionalSchemaConverter extends SchemaConverter {
32
+ condition(schema: AnySchema | undefined, options: SchemaConvertOptions): Promisable<boolean>;
33
+ }
34
+ declare class CompositeSchemaConverter implements SchemaConverter {
35
+ private readonly converters;
36
+ constructor(converters: readonly ConditionalSchemaConverter[]);
37
+ convert(schema: AnySchema | undefined, options: SchemaConvertOptions): Promise<[required: boolean, jsonSchema: JSONSchema]>;
38
+ }
39
+
40
+ interface OpenAPIGeneratorOptions extends StandardOpenAPIJsonSerializerOptions {
41
+ schemaConverters?: ConditionalSchemaConverter[];
42
+ }
43
+ interface OpenAPIGeneratorGenerateOptions extends Partial<Omit<OpenAPI.Document, 'openapi'>> {
44
+ /**
45
+ * Exclude procedures from the OpenAPI specification.
46
+ *
47
+ * @default () => false
48
+ */
49
+ exclude?: (procedure: AnyProcedure | AnyContractProcedure, path: readonly string[]) => boolean;
50
+ /**
51
+ * Common schemas to be used for $ref resolution.
52
+ */
53
+ commonSchemas?: Record<string, {
54
+ /**
55
+ * Determines which schema definition to use when input and output schemas differ.
56
+ * This is needed because some schemas transform data differently between input and output,
57
+ * making it impossible to use a single $ref for both cases.
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * // This schema transforms a string input into a number output
62
+ * const Schema = z.string()
63
+ * .transform(v => Number(v))
64
+ * .pipe(z.number())
65
+ *
66
+ * // Input schema: { type: 'string' }
67
+ * // Output schema: { type: 'number' }
68
+ * ```
69
+ *
70
+ * When schemas differ between input and output, you must explicitly choose
71
+ * which version to use for the OpenAPI specification.
72
+ *
73
+ * @default 'input' - Uses the input schema definition by default
74
+ */
75
+ strategy?: SchemaConvertOptions['strategy'];
76
+ schema: AnySchema;
77
+ } | {
78
+ error: 'UndefinedError';
79
+ schema?: never;
80
+ }>;
81
+ }
82
+ /**
83
+ * The generator that converts oRPC routers/contracts to OpenAPI specifications.
84
+ *
85
+ * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
86
+ */
87
+ declare class OpenAPIGenerator {
88
+ #private;
89
+ private readonly serializer;
90
+ private readonly converter;
91
+ constructor(options?: OpenAPIGeneratorOptions);
92
+ /**
93
+ * Generates OpenAPI specifications from oRPC routers/contracts.
94
+ *
95
+ * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
96
+ */
97
+ generate(router: AnyContractRouter | AnyRouter, options?: OpenAPIGeneratorGenerateOptions): Promise<OpenAPI.Document>;
98
+ }
99
+
100
+ export { OpenAPIGenerator as b, CompositeSchemaConverter as e };
101
+ export type { ConditionalSchemaConverter as C, OpenAPIGeneratorOptions as O, SchemaConverterComponent as S, OpenAPIGeneratorGenerateOptions as a, SchemaConvertOptions as c, SchemaConverter as d };
@@ -1,8 +1,8 @@
1
- import { StandardOpenAPIJsonSerializerOptions } from '@orpc/openapi-client/standard';
1
+ import { StandardOpenAPIJsonSerializerOptions, StandardBracketNotationSerializerOptions } from '@orpc/openapi-client/standard';
2
2
  import { Context, Router } from '@orpc/server';
3
3
  import { StandardHandlerOptions, StandardHandler } from '@orpc/server/standard';
4
4
 
5
- interface StandardOpenAPIHandlerOptions<T extends Context> extends StandardHandlerOptions<T>, StandardOpenAPIJsonSerializerOptions {
5
+ interface StandardOpenAPIHandlerOptions<T extends Context> extends StandardHandlerOptions<T>, StandardOpenAPIJsonSerializerOptions, StandardBracketNotationSerializerOptions {
6
6
  }
7
7
  declare class StandardOpenAPIHandler<T extends Context> extends StandardHandler<T> {
8
8
  constructor(router: Router<any, T>, options: NoInfer<StandardOpenAPIHandlerOptions<T>>);
@@ -1,8 +1,8 @@
1
- import { StandardOpenAPIJsonSerializerOptions } from '@orpc/openapi-client/standard';
1
+ import { StandardOpenAPIJsonSerializerOptions, StandardBracketNotationSerializerOptions } from '@orpc/openapi-client/standard';
2
2
  import { Context, Router } from '@orpc/server';
3
3
  import { StandardHandlerOptions, StandardHandler } from '@orpc/server/standard';
4
4
 
5
- interface StandardOpenAPIHandlerOptions<T extends Context> extends StandardHandlerOptions<T>, StandardOpenAPIJsonSerializerOptions {
5
+ interface StandardOpenAPIHandlerOptions<T extends Context> extends StandardHandlerOptions<T>, StandardOpenAPIJsonSerializerOptions, StandardBracketNotationSerializerOptions {
6
6
  }
7
7
  declare class StandardOpenAPIHandler<T extends Context> extends StandardHandler<T> {
8
8
  constructor(router: Router<any, T>, options: NoInfer<StandardOpenAPIHandlerOptions<T>>);