@orpc/json-schema 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.
@@ -0,0 +1,380 @@
1
+ /**
2
+ * These utilities assume the schema has only one root-level `$defs` object
3
+ * and exclusively use absolute JSON pointers for `$ref` values.
4
+ */
5
+ import { get, isDeepEqual, omit, toArray } from '@orpc/shared';
6
+ import { JSON_SCHEMA_LOGIC_KEYWORDS } from './constants.js';
7
+ import { decodeJsonPointerSegment, encodeJsonPointerSegment, hoistRecursiveRefToDef, mapJsonSchemaRefs, resolveJsonSchemaRootLocalRef, } from './ref-utils.js';
8
+ import { ensureJsonSchemaObject, isJsonArraySchema, isUnconstrainedSchema } from './utils.js';
9
+ /**
10
+ * Moves a schema's `$defs` into the shared root map, renaming only the names whose bodies
11
+ * conflict with an already promoted def, and returns the schema body rebased onto `basePath`.
12
+ *
13
+ * Refs inside the promoted def bodies are rewritten too: they share the schema's namespace, so
14
+ * a rename left unapplied there would silently bind the body to another schema's defs.
15
+ */
16
+ function promoteJsonSchemaDefs(schema, mergedDefs, basePath) {
17
+ const { $defs, ...rootBody } = schema;
18
+ const renameMap = new Map();
19
+ /**
20
+ * `basePath` is where `rootBody` lands in the combined document, so pointers resolved against
21
+ * the original root are rebased onto it, while `#/$defs/` pointers follow the promoted defs.
22
+ */
23
+ const mapRef = (ref) => {
24
+ if (ref === '#') {
25
+ return basePath;
26
+ }
27
+ if (ref.startsWith('#/$defs/')) {
28
+ const [encodedName, ...segments] = ref.slice('#/$defs/'.length).split('/');
29
+ const newName = renameMap.get(decodeJsonPointerSegment(encodedName));
30
+ return newName === undefined
31
+ ? ref
32
+ : ['#/$defs', encodeJsonPointerSegment(newName), ...segments].join('/');
33
+ }
34
+ if (ref.startsWith('#/') &&
35
+ get(rootBody, ref.slice(2).split('/').map(decodeJsonPointerSegment)) !== undefined) {
36
+ return `${basePath}/${ref.slice(2)}`;
37
+ }
38
+ return ref;
39
+ };
40
+ const defs = Object.entries($defs ?? {}).filter(([, def]) => def !== undefined);
41
+ if (defs.length > 0) {
42
+ const promoted = new Map();
43
+ const reserved = new Set([...mergedDefs.keys(), ...defs.map(([name]) => name)]);
44
+ /**
45
+ * A def body must be rewritten into the merged namespace before it can be compared for
46
+ * deduplication, and each rename invalidates every body pointing at the renamed def, so
47
+ * keep rewriting until a full pass renames nothing.
48
+ */
49
+ for (let changed = true; changed;) {
50
+ changed = false;
51
+ for (const [name, def] of defs) {
52
+ const body = mapJsonSchemaRefs(def, mapRef);
53
+ promoted.set(name, body);
54
+ if (renameMap.has(name) ||
55
+ !mergedDefs.has(name) ||
56
+ isDeepEqual(mergedDefs.get(name), body)) {
57
+ continue;
58
+ }
59
+ let counter = 2;
60
+ while (reserved.has(`${name}${counter}`)) {
61
+ counter++;
62
+ }
63
+ reserved.add(`${name}${counter}`);
64
+ renameMap.set(name, `${name}${counter}`);
65
+ changed = true;
66
+ }
67
+ }
68
+ for (const [name, body] of promoted) {
69
+ mergedDefs.set(renameMap.get(name) ?? name, body);
70
+ }
71
+ }
72
+ return mapJsonSchemaRefs(rootBody, mapRef);
73
+ }
74
+ /**
75
+ * Combines multiple schemas under the requested composition keyword, promoting branch `$defs` to the root.
76
+ */
77
+ export function combineJsonSchemasWithComposition(keyword, schemas) {
78
+ if (schemas.length <= 1) {
79
+ return schemas[0] ?? true;
80
+ }
81
+ const mergedDefs = new Map();
82
+ const compositionBranches = [];
83
+ for (let i = 0; i < schemas.length; i++) {
84
+ const schema = schemas[i];
85
+ compositionBranches.push(typeof schema === 'boolean'
86
+ ? schema
87
+ : promoteJsonSchemaDefs(schema, mergedDefs, `#/${keyword}/${i}`));
88
+ }
89
+ const result = { [keyword]: compositionBranches };
90
+ if (mergedDefs.size > 0) {
91
+ result.$defs = Object.fromEntries(mergedDefs);
92
+ }
93
+ return result;
94
+ }
95
+ /**
96
+ * Combines object property entries back into a single object schema.
97
+ * When given, `additionalProperties` constrains every property the entries do not name.
98
+ */
99
+ export function combineJsonObjectSchemaEntries(entries, additionalProperties) {
100
+ const properties = new Map();
101
+ const required = [];
102
+ const mergedDefs = new Map();
103
+ for (const [name, propertySchema, optional] of entries) {
104
+ if (!optional) {
105
+ required.push(name);
106
+ }
107
+ properties.set(name, typeof propertySchema === 'boolean'
108
+ ? propertySchema
109
+ : promoteJsonSchemaDefs(propertySchema, mergedDefs, `#/properties/${encodeJsonPointerSegment(name)}`));
110
+ }
111
+ const schema = {
112
+ type: 'object',
113
+ properties: Object.fromEntries(properties),
114
+ };
115
+ if (required.length > 0) {
116
+ schema.required = required;
117
+ }
118
+ if (additionalProperties !== undefined) {
119
+ schema.additionalProperties =
120
+ typeof additionalProperties === 'boolean'
121
+ ? additionalProperties
122
+ : promoteJsonSchemaDefs(additionalProperties, mergedDefs, '#/additionalProperties');
123
+ }
124
+ if (mergedDefs.size > 0) {
125
+ schema.$defs = Object.fromEntries(mergedDefs);
126
+ }
127
+ return schema;
128
+ }
129
+ /**
130
+ * Parses an object schema, or a composition of object schemas, into property entries.
131
+ */
132
+ export function extractJsonObjectSchemaEntries(schema) {
133
+ schema = hoistRecursiveRefToDef(schema);
134
+ if (typeof schema !== 'object') {
135
+ return undefined;
136
+ }
137
+ const result = extractJsonObjectSchemaEntriesInternal(omit(schema, ['$defs']), schema.$defs, new Set());
138
+ if (!result.objectLike) {
139
+ return undefined;
140
+ }
141
+ return result.entries.map(([n, s, ...r]) => [n, withRootDefs(s, schema.$defs), ...r]);
142
+ }
143
+ /**
144
+ * Returns the `additionalProperties` an object schema declares at its root, following root-local refs,
145
+ * with the root `$defs` attached so it can be passed to {@link combineJsonObjectSchemaEntries}.
146
+ * Composition branches are not inspected, since their keyword only constrains that branch.
147
+ */
148
+ export function extractJsonObjectSchemaAdditionalProperties(schema) {
149
+ schema = hoistRecursiveRefToDef(schema);
150
+ if (typeof schema !== 'object') {
151
+ return undefined;
152
+ }
153
+ const resolved = resolveJsonSchemaRootLocalRef(schema);
154
+ if (typeof resolved !== 'object' || resolved.additionalProperties === undefined) {
155
+ return undefined;
156
+ }
157
+ return withRootDefs(resolved.additionalProperties, schema.$defs);
158
+ }
159
+ const JSON_SCHEMA_OBJECT_KEYWORDS = [
160
+ 'properties',
161
+ 'patternProperties',
162
+ 'additionalProperties',
163
+ 'required',
164
+ 'propertyNames',
165
+ 'minProperties',
166
+ 'maxProperties',
167
+ ];
168
+ /**
169
+ * Returns true when an object can stand for every value the schema describes: the schema constrains objects,
170
+ * by `type` or object keywords, composes only such schemas, or is unconstrained, since an object satisfies it.
171
+ * Unlike {@link extractJsonObjectSchemaEntries}, an unconstrained schema counts as object-like.
172
+ */
173
+ export function isJsonObjectLikeSchema(schema) {
174
+ return isJsonObjectLikeSchemaInternal(schema, typeof schema === 'object' ? schema.$defs : undefined, new Set());
175
+ }
176
+ function isJsonObjectLikeSchemaInternal(schema, $defs, followedRefs) {
177
+ if (typeof schema === 'object' && typeof schema.$ref === 'string') {
178
+ // a cycle never proves the schema describes an object
179
+ if (followedRefs.has(schema.$ref)) {
180
+ return false;
181
+ }
182
+ followedRefs = new Set(followedRefs).add(schema.$ref);
183
+ }
184
+ const resolved = resolveJsonSchemaRootLocalRef(schema, $defs);
185
+ if (typeof resolved === 'boolean') {
186
+ return true;
187
+ }
188
+ if (resolved.type !== undefined) {
189
+ return resolved.type === 'object';
190
+ }
191
+ if (JSON_SCHEMA_OBJECT_KEYWORDS.some((keyword) => keyword in resolved)) {
192
+ return true;
193
+ }
194
+ for (const keyword of ['allOf', 'anyOf', 'oneOf']) {
195
+ const members = resolved[keyword];
196
+ if (Array.isArray(members) && members.length > 0) {
197
+ return members.every((member) => isJsonObjectLikeSchemaInternal(member, $defs, followedRefs));
198
+ }
199
+ }
200
+ return isUnconstrainedSchema(resolved);
201
+ }
202
+ function extractJsonObjectSchemaEntriesInternal(schema, $defs, resolvingRefs) {
203
+ if (typeof schema !== 'object') {
204
+ return { entries: [], objectLike: false };
205
+ }
206
+ if (typeof schema.$ref === 'string') {
207
+ if (resolvingRefs.has(schema.$ref)) {
208
+ return { entries: [], objectLike: true };
209
+ }
210
+ const resolved = resolveJsonSchemaRootLocalRef(schema, $defs);
211
+ if (resolved !== schema) {
212
+ return extractJsonObjectSchemaEntriesInternal(resolved, $defs, new Set(resolvingRefs).add(schema.$ref));
213
+ }
214
+ }
215
+ const sources = [];
216
+ if (schema.properties) {
217
+ sources.push({
218
+ entries: Object.entries(schema.properties).map(([name, propertySchema]) => {
219
+ return [
220
+ name,
221
+ propertySchema,
222
+ !schema.required?.includes(name),
223
+ ];
224
+ }),
225
+ source: 'direct',
226
+ });
227
+ }
228
+ let objectLike = schema.type === 'object' ||
229
+ schema.properties !== undefined ||
230
+ schema.required !== undefined ||
231
+ schema.additionalProperties !== undefined;
232
+ for (const keyword of ['anyOf', 'oneOf', 'allOf']) {
233
+ const branches = schema[keyword];
234
+ if (branches === undefined) {
235
+ continue;
236
+ }
237
+ const branchResults = branches.map((branch) => extractJsonObjectSchemaEntriesInternal(branch, $defs, resolvingRefs));
238
+ if (branchResults.some((result) => !result.objectLike)) {
239
+ return { entries: [], objectLike: false };
240
+ }
241
+ const entriesByName = new Map();
242
+ for (const result of branchResults) {
243
+ for (const entry of result.entries) {
244
+ const entries = entriesByName.get(entry[0]);
245
+ if (entries) {
246
+ entries.push(entry);
247
+ }
248
+ else {
249
+ entriesByName.set(entry[0], [entry]);
250
+ }
251
+ }
252
+ }
253
+ objectLike = true;
254
+ sources.push({
255
+ entries: Array.from(entriesByName.entries()).map(([name, entries]) => {
256
+ const schemas = deduplicateJsonSchemas(entries.map((entry) => entry[1]));
257
+ const required = keyword === 'allOf'
258
+ ? entries.some((entry) => !entry[2])
259
+ : branchResults.every((result) => {
260
+ const entry = result.entries.find((item) => item[0] === name);
261
+ return entry !== undefined && !entry[2];
262
+ });
263
+ return [
264
+ name,
265
+ schemas.length === 1
266
+ ? schemas[0]
267
+ : keyword === 'allOf'
268
+ ? { allOf: schemas }
269
+ : { anyOf: schemas },
270
+ !required,
271
+ ];
272
+ }),
273
+ source: keyword,
274
+ });
275
+ }
276
+ const sourceEntries = new Map();
277
+ for (const { entries, source } of sources) {
278
+ for (const entry of entries) {
279
+ const existing = sourceEntries.get(entry[0]);
280
+ if (existing) {
281
+ existing[source] = entry;
282
+ }
283
+ else {
284
+ sourceEntries.set(entry[0], { [source]: entry });
285
+ }
286
+ }
287
+ }
288
+ return {
289
+ entries: Array.from(sourceEntries.entries()).map(([name, entries]) => {
290
+ const schemas = deduplicateJsonSchemas([entries.direct?.[1], entries.allOf?.[1], entries.anyOf?.[1], entries.oneOf?.[1]].filter((schema) => schema !== undefined));
291
+ return [
292
+ name,
293
+ schemas.length === 1 ? schemas[0] : { allOf: schemas },
294
+ !schema.required?.includes(name) &&
295
+ [entries.allOf, entries.anyOf, entries.oneOf].every((entry) => entry === undefined || entry[2]),
296
+ ];
297
+ }),
298
+ objectLike,
299
+ };
300
+ }
301
+ /**
302
+ * Flattens `anyOf` and `oneOf` unions when they are the only active constraints.
303
+ */
304
+ export function flattenJsonUnionSchema(schema) {
305
+ return deduplicateJsonSchemas(flattenJsonUnionSchemaInternal(schema, new Set()));
306
+ }
307
+ function flattenJsonUnionSchemaInternal(schema, resolvingRefs) {
308
+ if (typeof schema !== 'object') {
309
+ return [schema];
310
+ }
311
+ if (typeof schema.$ref === 'string') {
312
+ if (resolvingRefs.has(schema.$ref)) {
313
+ return [];
314
+ }
315
+ const resolved = resolveJsonSchemaRootLocalRef(schema);
316
+ if (resolved !== schema) {
317
+ const result = flattenJsonUnionSchemaInternal(resolved, new Set(resolvingRefs).add(schema.$ref));
318
+ if (result.length > 1) {
319
+ return result;
320
+ }
321
+ }
322
+ }
323
+ const { anyOf: _anyOf, oneOf: _oneOf, ...rest } = schema;
324
+ const entries = Object.entries(rest).filter(([, val]) => val !== undefined);
325
+ for (const keyword of ['anyOf', 'oneOf']) {
326
+ if (schema[keyword]) {
327
+ return schema[keyword].flatMap((s) => {
328
+ s = ensureJsonSchemaObject(s);
329
+ const mergedSchema = {
330
+ ...s,
331
+ ...Object.fromEntries(entries.filter(([key]) => s[key] === undefined)),
332
+ $defs: schema.$defs,
333
+ };
334
+ const conflicts = entries.filter(([key]) => s[key] !== undefined);
335
+ if (conflicts.length) {
336
+ mergedSchema.allOf = [...toArray(mergedSchema.allOf), Object.fromEntries(conflicts)];
337
+ }
338
+ return flattenJsonUnionSchemaInternal(mergedSchema, resolvingRefs);
339
+ });
340
+ }
341
+ }
342
+ return [schema];
343
+ }
344
+ /**
345
+ * Matches a union made of a single item schema and its array form.
346
+ */
347
+ export function matchArrayableJsonSchema(schema) {
348
+ const schemas = flattenJsonUnionSchema(schema);
349
+ if (schemas.length !== 2) {
350
+ return undefined;
351
+ }
352
+ const arraySchema = schemas.find(isJsonArraySchema);
353
+ if (arraySchema === undefined) {
354
+ return undefined;
355
+ }
356
+ const items1 = arraySchema.items ?? true;
357
+ const items2 = schemas.find((s) => s !== arraySchema);
358
+ const logicItem1 = Object.fromEntries(Object.entries(ensureJsonSchemaObject(items1)).filter(([key]) => JSON_SCHEMA_LOGIC_KEYWORDS.has(key)));
359
+ const logicItem2 = Object.fromEntries(Object.entries(ensureJsonSchemaObject(items2)).filter(([key]) => JSON_SCHEMA_LOGIC_KEYWORDS.has(key)));
360
+ if (!isDeepEqual(logicItem1, logicItem2)) {
361
+ return undefined;
362
+ }
363
+ return [items2, arraySchema];
364
+ }
365
+ export function deduplicateJsonSchemas(schemas) {
366
+ const result = [];
367
+ for (const schema of schemas) {
368
+ if (result.some((i) => isDeepEqual(i, schema))) {
369
+ continue;
370
+ }
371
+ result.push(schema);
372
+ }
373
+ return result;
374
+ }
375
+ function withRootDefs(schema, $defs) {
376
+ if (typeof schema === 'boolean' || !$defs) {
377
+ return schema;
378
+ }
379
+ return { ...schema, $defs };
380
+ }
@@ -0,0 +1,8 @@
1
+ import type { JsonSchemaKeywords } from './types.ts';
2
+ export declare const JSON_SCHEMA_LOGIC_KEYWORDS: Set<JsonSchemaKeywords | (string & {})>;
3
+ export declare const JSON_SCHEMA_PRIMITIVE_TYPES: Set<string>;
4
+ export declare const JSON_SCHEMA_RECORD_KEYWORDS: Set<string>;
5
+ /**
6
+ * Keywords whose values are literal instance data, never subschemas.
7
+ */
8
+ export declare const JSON_SCHEMA_LITERAL_KEYWORDS: Set<string>;
@@ -0,0 +1,66 @@
1
+ export const JSON_SCHEMA_LOGIC_KEYWORDS =
2
+ /* @__PURE__ */ new Set([
3
+ '$dynamicRef',
4
+ '$ref',
5
+ 'additionalItems',
6
+ 'additionalProperties',
7
+ 'allOf',
8
+ 'anyOf',
9
+ 'const',
10
+ 'contains',
11
+ 'contentEncoding',
12
+ 'contentMediaType',
13
+ 'contentSchema',
14
+ 'dependencies',
15
+ 'dependentRequired',
16
+ 'dependentSchemas',
17
+ 'else',
18
+ 'enum',
19
+ 'exclusiveMaximum',
20
+ 'exclusiveMinimum',
21
+ 'format',
22
+ 'if',
23
+ 'items',
24
+ 'maxContains',
25
+ 'maximum',
26
+ 'maxItems',
27
+ 'maxLength',
28
+ 'maxProperties',
29
+ 'minContains',
30
+ 'minimum',
31
+ 'minItems',
32
+ 'minLength',
33
+ 'minProperties',
34
+ 'multipleOf',
35
+ 'not',
36
+ 'oneOf',
37
+ 'pattern',
38
+ 'patternProperties',
39
+ 'prefixItems',
40
+ 'properties',
41
+ 'propertyNames',
42
+ 'required',
43
+ 'then',
44
+ 'type',
45
+ 'unevaluatedItems',
46
+ 'unevaluatedProperties',
47
+ 'uniqueItems',
48
+ ]);
49
+ export const JSON_SCHEMA_PRIMITIVE_TYPES = /* @__PURE__ */ new Set([
50
+ 'string',
51
+ 'number',
52
+ 'integer',
53
+ 'boolean',
54
+ 'null',
55
+ ]);
56
+ export const JSON_SCHEMA_RECORD_KEYWORDS = /* @__PURE__ */ new Set([
57
+ 'properties',
58
+ 'patternProperties',
59
+ 'dependentSchemas',
60
+ 'dependencies',
61
+ '$defs',
62
+ ]);
63
+ /**
64
+ * Keywords whose values are literal instance data, never subschemas.
65
+ */
66
+ export const JSON_SCHEMA_LITERAL_KEYWORDS = /* @__PURE__ */ new Set(['const', 'enum']);
@@ -0,0 +1,29 @@
1
+ import type { AnySchema } from '@orpc/contract';
2
+ import type { JsonSchema } from './types.ts';
3
+ /**
4
+ * The conversion direction: `input` targets the schema's input type, `output` targets its output type.
5
+ *
6
+ * @see {@link https://orpc.dev/docs/integrations/standard-schema | Standard Schema Integration}
7
+ */
8
+ export type JsonSchemaConverterDirection = 'input' | 'output';
9
+ /**
10
+ * Interface for converting validation schemas into JSON Schema representations,
11
+ * used by tools such as the OpenAPI Generator and Smart Coercion plugins.
12
+ *
13
+ * @see {@link https://orpc.dev/docs/integrations/standard-schema | Standard Schema Integration}
14
+ */
15
+ export interface JsonSchemaConverter {
16
+ /**
17
+ * Determines whether this converter can handle the given schema.
18
+ */
19
+ condition(schema: AnySchema | undefined, direction: JsonSchemaConverterDirection): boolean;
20
+ /**
21
+ * Converts an ORPC schema to a JSON Schema representation.
22
+ */
23
+ convert(schema: AnySchema | undefined, direction: JsonSchemaConverterDirection): [jsonSchema: JsonSchema, optional: boolean];
24
+ }
25
+ export declare class DelegatingJsonSchemaConverter implements Pick<JsonSchemaConverter, 'convert'> {
26
+ private readonly converters;
27
+ constructor(converters?: JsonSchemaConverter[]);
28
+ convert(schema: AnySchema | undefined, direction: JsonSchemaConverterDirection): [jsonSchema: JsonSchema, optional: boolean];
29
+ }
@@ -0,0 +1,14 @@
1
+ export class DelegatingJsonSchemaConverter {
2
+ converters;
3
+ constructor(converters = []) {
4
+ this.converters = converters;
5
+ }
6
+ convert(schema, direction) {
7
+ for (const converter of this.converters) {
8
+ if (converter.condition(schema, direction)) {
9
+ return converter.convert(schema, direction);
10
+ }
11
+ }
12
+ return [{}, true];
13
+ }
14
+ }