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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +6 -7
  2. package/dist/adapters/aws-lambda/index.d.ts +10 -22
  3. package/dist/adapters/aws-lambda/index.js +1 -0
  4. package/dist/adapters/aws-lambda/openapi-handler.d.ts +18 -0
  5. package/dist/adapters/aws-lambda/openapi-handler.js +18 -0
  6. package/dist/adapters/fastify/index.d.ts +1 -23
  7. package/dist/adapters/fastify/index.js +1 -0
  8. package/dist/adapters/fastify/openapi-handler.d.ts +15 -0
  9. package/dist/adapters/fastify/openapi-handler.js +15 -0
  10. package/dist/adapters/fetch/index.d.ts +2 -37
  11. package/dist/adapters/fetch/index.js +2 -0
  12. package/dist/adapters/fetch/openapi-handler.d.ts +15 -0
  13. package/dist/adapters/fetch/openapi-handler.js +15 -0
  14. package/dist/adapters/fetch/openapi-link.d.ts +21 -0
  15. package/dist/adapters/fetch/openapi-link.js +20 -0
  16. package/dist/adapters/node/index.d.ts +1 -23
  17. package/dist/adapters/node/index.js +1 -0
  18. package/dist/adapters/node/openapi-handler.d.ts +15 -0
  19. package/dist/adapters/node/openapi-handler.js +15 -0
  20. package/dist/adapters/standard/index.d.ts +3 -56
  21. package/dist/adapters/standard/index.js +3 -0
  22. package/dist/adapters/standard/openapi-handler-codec.d.ts +62 -0
  23. package/dist/adapters/standard/openapi-handler-codec.js +220 -0
  24. package/dist/adapters/standard/{index.d.mts → openapi-link-codec.d.ts} +25 -19
  25. package/dist/adapters/standard/openapi-link-codec.js +405 -0
  26. package/dist/adapters/standard/openapi-matcher.d.ts +29 -0
  27. package/dist/adapters/standard/openapi-matcher.js +108 -0
  28. package/dist/adapters/standard/utils.d.ts +4 -0
  29. package/dist/adapters/standard/utils.js +47 -0
  30. package/dist/bracket-notation.d.ts +26 -0
  31. package/dist/bracket-notation.js +185 -0
  32. package/dist/client-factory.d.ts +24 -0
  33. package/dist/client-factory.js +13 -0
  34. package/dist/constants.d.ts +4 -0
  35. package/dist/constants.js +4 -0
  36. package/dist/extensions/route.d.ts +3 -7
  37. package/dist/extensions/route.js +12 -0
  38. package/dist/helpers/{index.d.mts → form-data.d.ts} +2 -4
  39. package/dist/helpers/form-data.js +90 -0
  40. package/dist/helpers/index.d.ts +1 -59
  41. package/dist/helpers/index.js +1 -0
  42. package/dist/index.d.ts +12 -165
  43. package/dist/index.js +11 -0
  44. package/dist/{shared/openapi.zGZlCOwp.d.mts → meta.d.ts} +14 -18
  45. package/dist/meta.js +84 -0
  46. package/dist/openapi-generator-components.d.ts +31 -0
  47. package/dist/openapi-generator-components.js +275 -0
  48. package/dist/openapi-generator-operation.d.ts +34 -0
  49. package/dist/openapi-generator-operation.js +469 -0
  50. package/dist/openapi-generator.d.ts +92 -0
  51. package/dist/openapi-generator.js +147 -0
  52. package/dist/openapi-json-serializer.d.ts +79 -0
  53. package/dist/openapi-json-serializer.js +260 -0
  54. package/dist/openapi-serializer.d.ts +43 -0
  55. package/dist/openapi-serializer.js +93 -0
  56. package/dist/plugins/index.d.ts +1 -121
  57. package/dist/plugins/index.js +1 -0
  58. package/dist/plugins/{index.d.mts → openapi-reference.d.ts} +15 -21
  59. package/dist/plugins/openapi-reference.js +187 -0
  60. package/dist/router-utils.d.ts +20 -0
  61. package/dist/router-utils.js +36 -0
  62. package/dist/types.d.ts +31 -0
  63. package/dist/types.js +1 -0
  64. package/dist/utils.d.ts +14 -0
  65. package/dist/utils.js +47 -0
  66. package/package.json +69 -71
  67. package/dist/adapters/aws-lambda/index.d.mts +0 -27
  68. package/dist/adapters/aws-lambda/index.mjs +0 -21
  69. package/dist/adapters/fastify/index.d.mts +0 -23
  70. package/dist/adapters/fastify/index.mjs +0 -21
  71. package/dist/adapters/fetch/index.d.mts +0 -37
  72. package/dist/adapters/fetch/index.mjs +0 -34
  73. package/dist/adapters/node/index.d.mts +0 -23
  74. package/dist/adapters/node/index.mjs +0 -21
  75. package/dist/adapters/standard/index.mjs +0 -12
  76. package/dist/extensions/route.d.mts +0 -41
  77. package/dist/extensions/route.mjs +0 -14
  78. package/dist/helpers/index.mjs +0 -39
  79. package/dist/index.d.mts +0 -166
  80. package/dist/index.mjs +0 -780
  81. package/dist/plugins/index.mjs +0 -167
  82. package/dist/shared/openapi.B9PQzqBn.mjs +0 -49
  83. package/dist/shared/openapi.CQkXu1nY.mjs +0 -366
  84. package/dist/shared/openapi.Covi8zVE.d.mts +0 -33
  85. package/dist/shared/openapi.Covi8zVE.d.ts +0 -33
  86. package/dist/shared/openapi.DfmCR1pB.d.mts +0 -94
  87. package/dist/shared/openapi.DtEVcxuW.mjs +0 -149
  88. package/dist/shared/openapi.E3ZBiweM.mjs +0 -353
  89. package/dist/shared/openapi.Y4K_-I5W.d.ts +0 -94
  90. package/dist/shared/openapi.YMRD3b4R.d.mts +0 -157
  91. package/dist/shared/openapi.YMRD3b4R.d.ts +0 -157
  92. package/dist/shared/openapi.g7ucL05o.mjs +0 -410
  93. package/dist/shared/openapi.zGZlCOwp.d.ts +0 -329
@@ -1,10 +1,9 @@
1
- import { AnySchema, ErrorMap, MetaPlugin, AnyProcedureContract } from '@orpc/contract';
2
- import { Lazy } from '@orpc/server';
3
- import { Value } from '@orpc/shared';
4
- import { StandardBodyHint } from '@standard-server/core';
5
- import * as OpenAPIV3_2 from '@openapi-spec/types/v3.2';
6
-
7
- interface OpenAPIMeta {
1
+ import type { AnyProcedureContract, AnySchema, ErrorMap, MetaPlugin } from '@orpc/contract';
2
+ import type { Lazy } from '@orpc/server';
3
+ import type { Value } from '@orpc/shared';
4
+ import type { StandardBodyHint } from '@standard-server/core';
5
+ import type { OpenAPIV3_2 } from './types.ts';
6
+ export interface OpenAPIMeta {
8
7
  /**
9
8
  * HTTP method accepted by this procedure.
10
9
  *
@@ -288,22 +287,22 @@ interface OpenAPIMeta {
288
287
  */
289
288
  prefix?: `/${string}` | undefined;
290
289
  }
291
- interface OpenAPIMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
290
+ export interface OpenAPIMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
292
291
  name: '~openapi';
293
292
  }
294
- interface OpenAPIMethodMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
293
+ export interface OpenAPIMethodMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
295
294
  name: '~openapi/method';
296
295
  }
297
- interface OpenAPIPathMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
296
+ export interface OpenAPIPathMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
298
297
  name: '~openapi/path';
299
298
  }
300
- interface OpenAPISpecMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
299
+ export interface OpenAPISpecMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
301
300
  name: '~openapi/spec';
302
301
  }
303
- interface OpenAPIPrefixMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
302
+ export interface OpenAPIPrefixMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
304
303
  name: '~openapi/prefix';
305
304
  }
306
- interface OpenAPIFunction {
305
+ export interface OpenAPIFunction {
307
306
  (meta: OpenAPIMeta): OpenAPIMetaPlugin<any, any, any>;
308
307
  method(method: OpenAPIMeta['method']): OpenAPIMethodMetaPlugin<any, any, any>;
309
308
  path(method: OpenAPIMeta['path']): OpenAPIPathMetaPlugin<any, any, any>;
@@ -317,13 +316,10 @@ interface OpenAPIFunction {
317
316
  * @see {@link https://orpc.dev/docs/openapi/routing | OpenAPI Routing}
318
317
  * @see {@link https://orpc.dev/docs/openapi/specification | OpenAPI Specification}
319
318
  */
320
- declare const openapi: OpenAPIFunction;
319
+ export declare const openapi: OpenAPIFunction;
321
320
  /**
322
321
  * Retrieves the OpenAPI metadata attached to a procedure or router, or `undefined` if not set.
323
322
  *
324
323
  * @see {@link https://orpc.dev/docs/rpc/handler#enabling-the-get-method | RPC Handler - Enabling the GET Method}
325
324
  */
326
- declare function getOpenAPIMeta(procedureOrLazy: AnyProcedureContract | Lazy<any>): OpenAPIMeta | undefined;
327
-
328
- export { getOpenAPIMeta as g, openapi as o };
329
- export type { OpenAPIMeta as O, OpenAPIFunction as a, OpenAPIMetaPlugin as b, OpenAPIMethodMetaPlugin as c, OpenAPIPathMetaPlugin as d, OpenAPIPrefixMetaPlugin as e, OpenAPISpecMetaPlugin as f };
325
+ export declare function getOpenAPIMeta(procedureOrLazy: AnyProcedureContract | Lazy<any>): OpenAPIMeta | undefined;
package/dist/meta.js ADDED
@@ -0,0 +1,84 @@
1
+ import { mergeHttpPath } from '@orpc/shared';
2
+ /**
3
+ * Creates OpenAPI meta plugins that control how a procedure is exposed over HTTP,
4
+ * such as its method, path, prefix, and OpenAPI operation spec.
5
+ *
6
+ * @see {@link https://orpc.dev/docs/openapi/routing | OpenAPI Routing}
7
+ * @see {@link https://orpc.dev/docs/openapi/specification | OpenAPI Specification}
8
+ */
9
+ export const openapi = (incoming) => ({
10
+ name: '~openapi',
11
+ init(meta) {
12
+ const existing = meta['~openapi'];
13
+ const tags = existing?.tags && incoming.tags
14
+ ? [...existing.tags, ...incoming.tags]
15
+ : 'tags' in incoming
16
+ ? incoming.tags
17
+ : existing?.tags;
18
+ const queryStyles = existing?.queryStyles && incoming.queryStyles
19
+ ? { ...existing.queryStyles, ...incoming.queryStyles }
20
+ : 'queryStyles' in incoming
21
+ ? incoming.queryStyles
22
+ : existing?.queryStyles;
23
+ const paramsStyles = existing?.paramsStyles && incoming.paramsStyles
24
+ ? { ...existing.paramsStyles, ...incoming.paramsStyles }
25
+ : 'paramsStyles' in incoming
26
+ ? incoming.paramsStyles
27
+ : existing?.paramsStyles;
28
+ const existingSpec = existing?.spec;
29
+ const incomingSpec = incoming.spec;
30
+ // AVOID a function spec, it requires the current spec as an argument, triggering an extra auto-generation step.
31
+ const spec = typeof existingSpec === 'function' && typeof incomingSpec === 'function'
32
+ ? (current) => incomingSpec(existingSpec(current))
33
+ : typeof existingSpec === 'function' && typeof incomingSpec === 'object'
34
+ ? existingSpec(incomingSpec)
35
+ : typeof existingSpec === 'object' && typeof incomingSpec === 'function'
36
+ ? incomingSpec(existingSpec)
37
+ : 'spec' in incoming
38
+ ? incomingSpec
39
+ : existingSpec;
40
+ const prefix = existing?.prefix && incoming.prefix
41
+ ? mergeHttpPath(existing.prefix, incoming.prefix)
42
+ : 'prefix' in incoming
43
+ ? incoming.prefix
44
+ : existing?.prefix;
45
+ // TODO: throw if incoming.path missing dynamic from existing.path
46
+ const merged = {
47
+ ...existing,
48
+ ...incoming,
49
+ tags,
50
+ queryStyles,
51
+ paramsStyles,
52
+ spec,
53
+ prefix,
54
+ };
55
+ return {
56
+ ...meta,
57
+ '~openapi': merged,
58
+ };
59
+ },
60
+ });
61
+ openapi.method = (method) => ({
62
+ ...openapi({ method }),
63
+ name: '~openapi/method',
64
+ });
65
+ openapi.path = (path) => ({
66
+ ...openapi({ path }),
67
+ name: '~openapi/path',
68
+ });
69
+ openapi.spec = (spec) => ({
70
+ ...openapi({ spec }),
71
+ name: '~openapi/spec',
72
+ });
73
+ openapi.prefix = (prefix) => ({
74
+ ...openapi({ prefix }),
75
+ name: '~openapi/prefix',
76
+ });
77
+ /**
78
+ * Retrieves the OpenAPI metadata attached to a procedure or router, or `undefined` if not set.
79
+ *
80
+ * @see {@link https://orpc.dev/docs/rpc/handler#enabling-the-get-method | RPC Handler - Enabling the GET Method}
81
+ */
82
+ export function getOpenAPIMeta(procedureOrLazy) {
83
+ return procedureOrLazy['~orpc'].meta['~openapi'];
84
+ }
@@ -0,0 +1,31 @@
1
+ import type { JsonSchema, JsonSchemaConverterDirection } from '@orpc/json-schema';
2
+ import type { OpenAPIV3_2 } from './types.ts';
3
+ /**
4
+ * Collects reusable schemas into `doc.components.schemas`.
5
+ *
6
+ * Equivalent schemas (including recursive ones) reuse a single component, and different
7
+ * schemas competing for the same name get direction-suffixed or numbered postfixes.
8
+ */
9
+ export declare class OpenAPIComponentRegistry {
10
+ private readonly doc;
11
+ private readonly componentName;
12
+ /**
13
+ * The unsanitized name each minted component was requested under, so distinct names
14
+ * that sanitize to the same key (`User Profile`, `User_Profile`) are never merged.
15
+ * Components the registry did not mint are reusable only when the requested name needs
16
+ * no sanitizing, which keeps `base.components` family reuse (`Planet`, `Planet2`) intact.
17
+ */
18
+ private readonly componentSources;
19
+ constructor(doc: OpenAPIV3_2.OpenAPIObject, componentName: ((defName: string, defSchema: JsonSchema) => string) | undefined);
20
+ /**
21
+ * Registers `schema` as a component under `preferredName` (or an equivalent/postfixed name)
22
+ * and returns a `$ref` to it.
23
+ */
24
+ register(preferredName: string, schema: Exclude<JsonSchema, boolean>): JsonSchema;
25
+ /**
26
+ * Moves a schema's root-level `$defs` into `doc.components.schemas` and rewrites
27
+ * its refs accordingly.
28
+ */
29
+ hoistDefs(schema: JsonSchema, direction?: JsonSchemaConverterDirection): JsonSchema;
30
+ toOpenAPISchema(schema: JsonSchema, direction?: JsonSchemaConverterDirection): OpenAPIV3_2.SchemaObject;
31
+ }
@@ -0,0 +1,275 @@
1
+ import { decodeJsonPointerSegment, encodeJsonPointerSegment, ensureJsonSchemaObject, getJsonSchemaKeywordKind, mapJsonSchemaRefs, } from '@orpc/json-schema';
2
+ import { getOwn, isDeepEqual, isPlainObject, setOwn } from '@orpc/shared';
3
+ const DEFS_REF_PREFIX = '#/$defs/';
4
+ const COMPONENTS_REF_PREFIX = '#/components/schemas/';
5
+ /**
6
+ * Replaces characters OpenAPI does not allow in component keys (`^[a-zA-Z0-9._-]+$`) with `_`.
7
+ * Minted names are always valid keys, so refs to them need no JSON Pointer or URI escaping.
8
+ */
9
+ function toValidComponentName(name) {
10
+ return name.replace(/[^a-zA-Z0-9._-]/gu, '_') || '_';
11
+ }
12
+ /**
13
+ * Collects reusable schemas into `doc.components.schemas`.
14
+ *
15
+ * Equivalent schemas (including recursive ones) reuse a single component, and different
16
+ * schemas competing for the same name get direction-suffixed or numbered postfixes.
17
+ */
18
+ export class OpenAPIComponentRegistry {
19
+ doc;
20
+ componentName;
21
+ /**
22
+ * The unsanitized name each minted component was requested under, so distinct names
23
+ * that sanitize to the same key (`User Profile`, `User_Profile`) are never merged.
24
+ * Components the registry did not mint are reusable only when the requested name needs
25
+ * no sanitizing, which keeps `base.components` family reuse (`Planet`, `Planet2`) intact.
26
+ */
27
+ componentSources = new Map();
28
+ constructor(doc, componentName) {
29
+ this.doc = doc;
30
+ this.componentName = componentName;
31
+ }
32
+ /**
33
+ * Registers `schema` as a component under `preferredName` (or an equivalent/postfixed name)
34
+ * and returns a `$ref` to it.
35
+ */
36
+ register(preferredName, schema) {
37
+ const { $defs, ...body } = schema;
38
+ // the schema can carry its own local $defs, keep the registered name unique among them
39
+ let defName = preferredName;
40
+ if ($defs) {
41
+ for (let i = 2; Object.hasOwn($defs, defName); i++) {
42
+ defName = `${preferredName}${i}`;
43
+ }
44
+ }
45
+ return this.hoistDefs({
46
+ $defs: { ...$defs, [defName]: body },
47
+ $ref: `${DEFS_REF_PREFIX}${encodeJsonPointerSegment(defName)}`,
48
+ });
49
+ }
50
+ /**
51
+ * Moves a schema's root-level `$defs` into `doc.components.schemas` and rewrites
52
+ * its refs accordingly.
53
+ */
54
+ hoistDefs(schema, direction) {
55
+ if (typeof schema !== 'object' || !schema.$defs) {
56
+ return schema;
57
+ }
58
+ const { $defs, ...rest } = schema;
59
+ const defs = new Map();
60
+ for (const defName of Object.keys($defs)) {
61
+ const defSchema = $defs[defName];
62
+ if (defSchema !== undefined) {
63
+ defs.set(defName, ensureJsonSchemaObject(defSchema));
64
+ }
65
+ }
66
+ if (defs.size === 0) {
67
+ return schema;
68
+ }
69
+ this.doc.components ??= {};
70
+ this.doc.components.schemas ??= {};
71
+ const componentsSchemas = this.doc.components.schemas;
72
+ const renameMap = new Map();
73
+ const pendingSchemas = [];
74
+ for (const [defName, cleanSchema] of defs) {
75
+ const sourceName = this.componentName ? this.componentName(defName, cleanSchema) : defName;
76
+ const preferredName = toValidComponentName(sourceName);
77
+ const [componentName, reuseExisting] = resolveComponentName(componentsSchemas, new Set(renameMap.values()), defName, preferredName, (name) => (this.componentSources.get(name) ?? preferredName) === sourceName, defs, direction);
78
+ renameMap.set(defName, componentName);
79
+ if (!reuseExisting) {
80
+ this.componentSources.set(componentName, sourceName);
81
+ pendingSchemas.push({ cleanSchema, componentName });
82
+ }
83
+ }
84
+ for (const { cleanSchema, componentName } of pendingSchemas) {
85
+ setOwn(componentsSchemas, componentName, rewriteComponentSchemaRefs(cleanSchema, renameMap));
86
+ }
87
+ return rewriteComponentSchemaRefs(rest, renameMap);
88
+ }
89
+ toOpenAPISchema(schema, direction) {
90
+ return ensureJsonSchemaObject(this.hoistDefs(schema, direction));
91
+ }
92
+ }
93
+ /**
94
+ * Walks a def's name family until it finds an equivalent existing component to reuse or
95
+ * runs out of family members, then fills the first free mintable slot. Equal schemas under
96
+ * unrelated names are never merged: a different name signals a different purpose.
97
+ *
98
+ * The family is the bare name, the direction-suffixed names when the conversion direction
99
+ * is known, then plain numeric postfixes (`Planet`, `PlanetOutput`, `PlanetInput`,
100
+ * `Planet2`, ...). Every member is checked for reuse, including the opposite direction,
101
+ * but new components are only minted under the bare, own-direction, or numeric names.
102
+ */
103
+ function resolveComponentName(componentsSchemas, claimedNames, defName, preferredName, isReusable, defs, direction) {
104
+ let mintName;
105
+ for (let i = 1;; i++) {
106
+ const [componentName, mintable, tail] = componentNameCandidate(preferredName, direction, i);
107
+ const existingSchema = getOwn(componentsSchemas, componentName);
108
+ if (existingSchema === undefined) {
109
+ // a sibling def can claim a slot before its schema is written, keep probing past it
110
+ if (mintable && !claimedNames.has(componentName)) {
111
+ mintName ??= componentName;
112
+ if (tail) {
113
+ return [mintName, false];
114
+ }
115
+ }
116
+ continue;
117
+ }
118
+ if (isReusable(componentName) &&
119
+ areSchemaRefsEquivalentForReuse(DEFS_REF_PREFIX + encodeJsonPointerSegment(defName), COMPONENTS_REF_PREFIX + componentName, {
120
+ defs,
121
+ componentsSchemas,
122
+ candidateToExistingKeys: new Map(),
123
+ pairedExistingKeys: new Set(),
124
+ visited: new WeakMap(),
125
+ })) {
126
+ return [componentName, true];
127
+ }
128
+ }
129
+ }
130
+ function componentNameCandidate(preferredName, direction, attempt) {
131
+ if (attempt === 1) {
132
+ return [preferredName, true, false];
133
+ }
134
+ if (direction !== undefined) {
135
+ if (attempt === 2) {
136
+ return [`${preferredName}${direction === 'input' ? 'Input' : 'Output'}`, true, false];
137
+ }
138
+ // the opposite direction is only ever reused, never minted
139
+ if (attempt === 3) {
140
+ return [`${preferredName}${direction === 'input' ? 'Output' : 'Input'}`, false, false];
141
+ }
142
+ return [`${preferredName}${attempt - 2}`, true, true];
143
+ }
144
+ return [`${preferredName}${attempt}`, true, true];
145
+ }
146
+ function definedKeysOf(object) {
147
+ // `undefined`-valued keys (e.g. `default: undefined`) are stripped during serialization,
148
+ // so they must not affect equivalence against components from serialized documents
149
+ return (Object.keys(object)
150
+ .filter((key) => object[key] !== undefined)
151
+ // oxlint-disable-next-line unicorn/no-array-sort
152
+ .sort());
153
+ }
154
+ function isSchemaContainer(value) {
155
+ return Array.isArray(value) || isPlainObject(value);
156
+ }
157
+ function areSchemasEquivalentForReuse(candidate, existing, ctx, position = 'schema') {
158
+ if (candidate === existing) {
159
+ return true;
160
+ }
161
+ // Only arrays and plain objects carry schema structure; primitives and values like Date are compared as a whole
162
+ if (!isSchemaContainer(candidate) || !isSchemaContainer(existing)) {
163
+ return isDeepEqual(candidate, existing);
164
+ }
165
+ const seenExisting = ctx.visited.get(candidate);
166
+ if (seenExisting?.has(existing)) {
167
+ return true;
168
+ }
169
+ if (seenExisting) {
170
+ seenExisting.add(existing);
171
+ }
172
+ else {
173
+ ctx.visited.set(candidate, new WeakSet([existing]));
174
+ }
175
+ if (Array.isArray(candidate) || Array.isArray(existing)) {
176
+ if (!Array.isArray(candidate) ||
177
+ !Array.isArray(existing) ||
178
+ candidate.length !== existing.length) {
179
+ return false;
180
+ }
181
+ return candidate.every((item, index) => areSchemasEquivalentForReuse(item, existing[index], ctx, position));
182
+ }
183
+ return areObjectsEquivalentForReuse(candidate, existing, (key, candidateValue, existingValue) => {
184
+ if (position === 'data') {
185
+ return areSchemasEquivalentForReuse(candidateValue, existingValue, ctx, 'data');
186
+ }
187
+ switch (getJsonSchemaKeywordKind(key, candidateValue, position === 'schema')) {
188
+ case 'ref':
189
+ return areRefValuesEquivalentForReuse(candidateValue, existingValue, ctx);
190
+ case 'discriminator':
191
+ return areDiscriminatorsEquivalentForReuse(candidateValue, existingValue, ctx);
192
+ case 'schema':
193
+ return areSchemasEquivalentForReuse(candidateValue, existingValue, ctx);
194
+ case 'schema-record':
195
+ return areSchemasEquivalentForReuse(candidateValue, existingValue, ctx, 'schema-record');
196
+ default:
197
+ return areSchemasEquivalentForReuse(candidateValue, existingValue, ctx, 'data');
198
+ }
199
+ });
200
+ }
201
+ function areObjectsEquivalentForReuse(candidate, existing, areValuesEquivalent) {
202
+ const candidateKeys = definedKeysOf(candidate);
203
+ return (isDeepEqual(candidateKeys, definedKeysOf(existing)) &&
204
+ candidateKeys.every((key) => areValuesEquivalent(key, candidate[key], existing[key])));
205
+ }
206
+ function areRefValuesEquivalentForReuse(candidate, existing, ctx) {
207
+ if (typeof candidate === 'string' && typeof existing === 'string') {
208
+ return areSchemaRefsEquivalentForReuse(candidate, existing, ctx);
209
+ }
210
+ return areSchemasEquivalentForReuse(candidate, existing, ctx, 'data');
211
+ }
212
+ /**
213
+ * `discriminator.mapping`/`defaultMapping` values can be refs, which are rewritten during hoisting like `$ref`,
214
+ * so they must be compared by their targets rather than by their (prefix-dependent) strings.
215
+ * Values that are not refs (bare schema names) still compare by string equality.
216
+ */
217
+ function areDiscriminatorsEquivalentForReuse(candidate, existing, ctx) {
218
+ if (!isPlainObject(candidate) || !isPlainObject(existing)) {
219
+ return areSchemasEquivalentForReuse(candidate, existing, ctx, 'data');
220
+ }
221
+ return areObjectsEquivalentForReuse(candidate, existing, (key, candidateValue, existingValue) => {
222
+ if (key === 'mapping' && isPlainObject(candidateValue) && isPlainObject(existingValue)) {
223
+ return areObjectsEquivalentForReuse(candidateValue, existingValue, (_, candidateRef, existingRef) => areRefValuesEquivalentForReuse(candidateRef, existingRef, ctx));
224
+ }
225
+ if (key === 'defaultMapping') {
226
+ return areRefValuesEquivalentForReuse(candidateValue, existingValue, ctx);
227
+ }
228
+ return areSchemasEquivalentForReuse(candidateValue, existingValue, ctx, 'data');
229
+ });
230
+ }
231
+ function parseRefName(ref, prefix) {
232
+ if (!ref.startsWith(prefix)) {
233
+ return undefined;
234
+ }
235
+ return ref.slice(prefix.length).split('/').map(decodeJsonPointerSegment).join('/');
236
+ }
237
+ function resolveNamedRef(ref, prefix, getNamed) {
238
+ const name = parseRefName(ref, prefix);
239
+ if (name === undefined) {
240
+ return undefined;
241
+ }
242
+ const schema = getNamed(name);
243
+ return schema === undefined ? undefined : { key: prefix + name, schema };
244
+ }
245
+ function areSchemaRefsEquivalentForReuse(candidateRef, existingRef, ctx) {
246
+ const getComponent = (name) => getOwn(ctx.componentsSchemas, name);
247
+ const candidate = resolveNamedRef(candidateRef, DEFS_REF_PREFIX, (name) => ctx.defs.get(name)) ??
248
+ resolveNamedRef(candidateRef, COMPONENTS_REF_PREFIX, getComponent);
249
+ const existing = resolveNamedRef(existingRef, COMPONENTS_REF_PREFIX, getComponent);
250
+ if (candidate === undefined || existing === undefined) {
251
+ return !candidate && !existing && candidateRef === existingRef;
252
+ }
253
+ const pairedExisting = ctx.candidateToExistingKeys.get(candidate.key);
254
+ if (pairedExisting !== existing.key) {
255
+ if (pairedExisting !== undefined || ctx.pairedExistingKeys.has(existing.key)) {
256
+ return false;
257
+ }
258
+ ctx.candidateToExistingKeys.set(candidate.key, existing.key);
259
+ ctx.pairedExistingKeys.add(existing.key);
260
+ }
261
+ return areSchemasEquivalentForReuse(candidate.schema, existing.schema, ctx);
262
+ }
263
+ function rewriteComponentSchemaRefs(schema, renameMap) {
264
+ return mapJsonSchemaRefs(schema, (ref) => {
265
+ const refName = parseRefName(ref, DEFS_REF_PREFIX);
266
+ if (refName === undefined) {
267
+ return ref;
268
+ }
269
+ const renamedName = renameMap.get(refName);
270
+ if (renamedName === undefined) {
271
+ return ref;
272
+ }
273
+ return COMPONENTS_REF_PREFIX + renamedName;
274
+ });
275
+ }
@@ -0,0 +1,34 @@
1
+ import type { AnyProcedureContract, AnySchema } from '@orpc/contract';
2
+ import type { JsonSchema, JsonSchemaConverterDirection } from '@orpc/json-schema';
3
+ import type { Value } from '@orpc/shared';
4
+ import type { OpenAPIMeta } from './meta.ts';
5
+ import type { OpenAPIComponentRegistry } from './openapi-generator-components.ts';
6
+ import type { OpenAPIV3_2 } from './types.ts';
7
+ import type { getDynamicPathParams } from './utils.ts';
8
+ export type DynamicPathParam = NonNullable<ReturnType<typeof getDynamicPathParams>>[number];
9
+ export declare class OpenAPIGeneratorError extends TypeError {
10
+ }
11
+ export interface OpenAPIErrorBodyDefinition {
12
+ code: string;
13
+ defaultMessage: string | undefined;
14
+ dataOptional: boolean;
15
+ dataJsonSchema: JsonSchema;
16
+ }
17
+ /**
18
+ * Everything the operation builders need from the surrounding `generate()` call.
19
+ */
20
+ export interface OpenAPIOperationContext {
21
+ registry: OpenAPIComponentRegistry;
22
+ convertSchemas: (schemas: AnySchema[] | undefined, direction: JsonSchemaConverterDirection) => [JsonSchema, boolean];
23
+ errorStatusMap: Record<string, number>;
24
+ errorResponseBodySchema: Value<JsonSchema | null | undefined, [
25
+ definedErrors: OpenAPIErrorBodyDefinition[],
26
+ status: number,
27
+ defaultSchema: () => JsonSchema
28
+ ]> | undefined;
29
+ errorResponseContentType: string;
30
+ }
31
+ export declare function toOpenAPIPath(path: `/${string}`, dynamicPathParams: DynamicPathParam[] | undefined): `/${string}`;
32
+ export declare function buildRequest(ctx: OpenAPIOperationContext, operation: OpenAPIV3_2.OperationObject, def: AnyProcedureContract['~orpc'], meta: OpenAPIMeta | undefined, dynamicPathParams: DynamicPathParam[] | undefined): void;
33
+ export declare function buildSuccessResponse(ctx: OpenAPIOperationContext, operation: OpenAPIV3_2.OperationObject, def: AnyProcedureContract['~orpc'], meta: OpenAPIMeta | undefined): void;
34
+ export declare function buildErrorResponse(ctx: OpenAPIOperationContext, operation: OpenAPIV3_2.OperationObject, def: AnyProcedureContract['~orpc']): void;