zod-openapi 5.0.0-beta.18 → 5.0.0-beta.2

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,1085 @@
1
+ "use strict";
2
+ const core = require("zod/v4/core");
3
+ const v4 = require("zod/v4");
4
+ const isAnyZodType = (schema) => typeof schema === "object" && schema !== null && "_zod" in schema;
5
+ const unwrapZodObject = (zodType, io, path) => {
6
+ const def = zodType._zod.def;
7
+ switch (def.type) {
8
+ case "object": {
9
+ return zodType;
10
+ }
11
+ case "lazy": {
12
+ return unwrapZodObject(def.getter(), io, path);
13
+ }
14
+ case "pipe": {
15
+ if (io === "input") {
16
+ return unwrapZodObject(def.in, io, path);
17
+ }
18
+ return unwrapZodObject(def.out, io, path);
19
+ }
20
+ }
21
+ throw new Error(
22
+ `Failed to unwrap ZodObject from type: ${zodType._zod.def.type} at ${path.join(" > ")}`
23
+ );
24
+ };
25
+ const isRequired = (zodType, io) => {
26
+ if (io === "input") {
27
+ return zodType._zod.optin === void 0;
28
+ }
29
+ return zodType._zod.optout === void 0;
30
+ };
31
+ const createParameter = (parameter, location, ctx, path) => {
32
+ var _a, _b;
33
+ const seenParameter = ctx.registry.parameters.seen.get(parameter);
34
+ if (seenParameter) {
35
+ return seenParameter;
36
+ }
37
+ const meta = v4.globalRegistry.get(parameter);
38
+ const name = (location == null ? void 0 : location.name) ?? ((_a = meta == null ? void 0 : meta.param) == null ? void 0 : _a.name);
39
+ const inLocation = (location == null ? void 0 : location.in) ?? ((_b = meta == null ? void 0 : meta.param) == null ? void 0 : _b.in);
40
+ if (!name || !inLocation) {
41
+ throw new Error(
42
+ `Parameter at ${path.join(" > ")} is missing \`.meta({ param: { name, in } })\` information`
43
+ );
44
+ }
45
+ const computedPath = [...path, inLocation, name].join(" > ");
46
+ const schemaObject = ctx.registry.schemas.setSchema(
47
+ computedPath,
48
+ parameter,
49
+ ctx.io
50
+ );
51
+ const { id, ...rest } = (meta == null ? void 0 : meta.param) ?? {};
52
+ const parameterObject = {
53
+ ...rest,
54
+ name,
55
+ in: inLocation,
56
+ schema: schemaObject
57
+ };
58
+ if (isRequired(parameter, ctx.io)) {
59
+ parameterObject.required = true;
60
+ }
61
+ if (!parameterObject.description && (meta == null ? void 0 : meta.description)) {
62
+ parameterObject.description = meta.description;
63
+ }
64
+ if (id) {
65
+ const ref = {
66
+ $ref: `#/components/parameters/${id}`
67
+ };
68
+ ctx.registry.parameters.seen.set(parameter, ref);
69
+ ctx.registry.parameters.ids.set(id, parameterObject);
70
+ return ref;
71
+ }
72
+ ctx.registry.parameters.seen.set(parameter, parameterObject);
73
+ return parameterObject;
74
+ };
75
+ const createManualParameters = (parameters, ctx, path) => {
76
+ if (!parameters) {
77
+ return void 0;
78
+ }
79
+ const parameterObjects = [];
80
+ for (const parameter of parameters) {
81
+ if (isAnyZodType(parameter)) {
82
+ const seenParameter = ctx.registry.parameters.seen.get(parameter);
83
+ if (seenParameter) {
84
+ parameterObjects.push(seenParameter);
85
+ continue;
86
+ }
87
+ const paramObject = createParameter(parameter, void 0, ctx, [
88
+ ...path,
89
+ "parameters"
90
+ ]);
91
+ parameterObjects.push(paramObject);
92
+ continue;
93
+ }
94
+ parameterObjects.push(parameter);
95
+ }
96
+ return parameterObjects;
97
+ };
98
+ const createParameters = (requestParams, ctx, path) => {
99
+ if (!requestParams) {
100
+ return void 0;
101
+ }
102
+ const parameterObjects = [];
103
+ for (const [location, schema] of Object.entries(requestParams ?? {})) {
104
+ if (!schema) {
105
+ continue;
106
+ }
107
+ const zodObject = unwrapZodObject(schema, ctx.io, path);
108
+ for (const [name, zodSchema] of Object.entries(zodObject._zod.def.shape)) {
109
+ const seenParameter = ctx.registry.parameters.seen.get(zodSchema);
110
+ if (seenParameter) {
111
+ parameterObjects.push(seenParameter);
112
+ continue;
113
+ }
114
+ const paramObject = createParameter(
115
+ zodSchema,
116
+ {
117
+ in: location,
118
+ name
119
+ },
120
+ ctx,
121
+ [...path, location, name]
122
+ );
123
+ parameterObjects.push(paramObject);
124
+ }
125
+ }
126
+ return parameterObjects;
127
+ };
128
+ const createMediaTypeObject = (mediaTypeObject, ctx, path) => {
129
+ const computedPath = path.join(" > ");
130
+ if (isAnyZodType(mediaTypeObject.schema)) {
131
+ const schemaObject = ctx.registry.schemas.setSchema(
132
+ computedPath,
133
+ mediaTypeObject.schema,
134
+ ctx.io
135
+ );
136
+ return {
137
+ ...mediaTypeObject,
138
+ schema: schemaObject
139
+ };
140
+ }
141
+ return mediaTypeObject;
142
+ };
143
+ const createContent = (content, ctx, path) => {
144
+ const contentObject = {};
145
+ for (const [mediaType, mediaTypeObject] of Object.entries(content)) {
146
+ if (mediaTypeObject) {
147
+ contentObject[mediaType] = createMediaTypeObject(mediaTypeObject, ctx, [
148
+ ...path,
149
+ mediaType
150
+ ]);
151
+ }
152
+ }
153
+ return contentObject;
154
+ };
155
+ const createRequestBody = (requestBody, ctx, path) => {
156
+ if (!requestBody) {
157
+ return void 0;
158
+ }
159
+ const seenRequestBody = ctx.registry.requestBodies.seen.get(requestBody);
160
+ if (seenRequestBody) {
161
+ return seenRequestBody;
162
+ }
163
+ const { content, id, ...rest } = requestBody;
164
+ const requestBodyObject = {
165
+ ...rest,
166
+ content: createContent(content, ctx, [...path, "content"])
167
+ };
168
+ if (id) {
169
+ const ref = {
170
+ $ref: `#/components/requestBodies/${id}`
171
+ };
172
+ ctx.registry.requestBodies.ids.set(id, requestBodyObject);
173
+ ctx.registry.requestBodies.seen.set(requestBody, ref);
174
+ return ref;
175
+ }
176
+ ctx.registry.requestBodies.seen.set(requestBody, requestBodyObject);
177
+ return requestBodyObject;
178
+ };
179
+ const createHeader = (header, ctx, path) => {
180
+ const seenHeader = ctx.registry.headers.seen.get(header);
181
+ if (seenHeader) {
182
+ return seenHeader;
183
+ }
184
+ const meta = v4.globalRegistry.get(header);
185
+ const { id, ...rest } = (meta == null ? void 0 : meta.header) ?? {};
186
+ const headerObject = rest;
187
+ if (isRequired(header, ctx.io)) {
188
+ headerObject.required = true;
189
+ }
190
+ if (!headerObject.description && (meta == null ? void 0 : meta.description)) {
191
+ headerObject.description = meta.description;
192
+ }
193
+ const computedPath = path.join(" > ");
194
+ headerObject.schema = ctx.registry.schemas.setSchema(
195
+ computedPath,
196
+ header,
197
+ ctx.io
198
+ );
199
+ if (id) {
200
+ const ref = {
201
+ $ref: `#/components/headers/${id}`
202
+ };
203
+ ctx.registry.headers.ids.set(id, headerObject);
204
+ ctx.registry.headers.seen.set(header, ref);
205
+ return ref;
206
+ }
207
+ ctx.registry.headers.seen.set(header, headerObject);
208
+ return headerObject;
209
+ };
210
+ const createHeaders = (headers, ctx, path) => {
211
+ if (!headers) {
212
+ return void 0;
213
+ }
214
+ if (isAnyZodType(headers)) {
215
+ const zodObject = unwrapZodObject(headers, ctx.io, path);
216
+ const headersObject = {};
217
+ for (const [key, zodSchema] of Object.entries(zodObject._zod.def.shape)) {
218
+ const header = createHeader(zodSchema, ctx, [...path, key]);
219
+ headersObject[key] = header;
220
+ }
221
+ return headersObject;
222
+ }
223
+ return headers;
224
+ };
225
+ const isISpecificationExtension = (key) => key.startsWith("x-");
226
+ const createResponse = (response, ctx, path) => {
227
+ const seenResponse = ctx.registry.responses.seen.get(response);
228
+ if (seenResponse) {
229
+ return seenResponse;
230
+ }
231
+ const { content, headers, id, ...rest } = response;
232
+ const responseObject = rest;
233
+ const maybeHeaders = createHeaders(headers, ctx, [...path, "headers"]);
234
+ if (maybeHeaders) {
235
+ responseObject.headers = maybeHeaders;
236
+ }
237
+ if (content) {
238
+ responseObject.content = createContent(content, ctx, [...path, "content"]);
239
+ }
240
+ if (id) {
241
+ const ref = {
242
+ $ref: `#/components/responses/${id}`
243
+ };
244
+ ctx.registry.responses.ids.set(id, responseObject);
245
+ ctx.registry.responses.seen.set(response, ref);
246
+ return ref;
247
+ }
248
+ ctx.registry.responses.seen.set(response, responseObject);
249
+ return responseObject;
250
+ };
251
+ const createResponses = (responses, ctx, path) => {
252
+ if (!responses) {
253
+ return void 0;
254
+ }
255
+ const responsesObject = {};
256
+ for (const [statusCode, response] of Object.entries(responses)) {
257
+ if (!response) {
258
+ continue;
259
+ }
260
+ if (isISpecificationExtension(statusCode)) {
261
+ responsesObject[statusCode] = response;
262
+ continue;
263
+ }
264
+ if ("$ref" in response) {
265
+ responsesObject[statusCode] = response;
266
+ continue;
267
+ }
268
+ const responseObject = createResponse(
269
+ response,
270
+ ctx,
271
+ [...path, statusCode]
272
+ );
273
+ responsesObject[statusCode] = responseObject;
274
+ }
275
+ return responsesObject;
276
+ };
277
+ const createOperation = (operationObject, registry, path) => {
278
+ const {
279
+ parameters,
280
+ requestParams,
281
+ requestBody,
282
+ responses,
283
+ callbacks,
284
+ ...rest
285
+ } = operationObject;
286
+ const operation = rest;
287
+ const maybeManualParameters = createManualParameters(
288
+ parameters,
289
+ {
290
+ registry,
291
+ io: "input"
292
+ },
293
+ [...path, "parameters"]
294
+ );
295
+ const maybeRequestParams = createParameters(
296
+ requestParams,
297
+ {
298
+ registry,
299
+ io: "input"
300
+ },
301
+ [...path, "requestParams"]
302
+ );
303
+ if (maybeRequestParams || maybeManualParameters) {
304
+ operation.parameters = [
305
+ ...maybeRequestParams ?? [],
306
+ ...maybeManualParameters ?? []
307
+ ];
308
+ }
309
+ const maybeRequestBody = createRequestBody(
310
+ requestBody,
311
+ {
312
+ registry,
313
+ io: "input"
314
+ },
315
+ [...path, "requestBody"]
316
+ );
317
+ if (maybeRequestBody) {
318
+ operation.requestBody = maybeRequestBody;
319
+ }
320
+ const maybeResponses = createResponses(
321
+ responses,
322
+ {
323
+ registry,
324
+ io: "output"
325
+ },
326
+ [...path, "responses"]
327
+ );
328
+ if (maybeResponses) {
329
+ operation.responses = maybeResponses;
330
+ }
331
+ const maybeCallbacks = createCallbacks(callbacks, registry, [
332
+ ...path,
333
+ "callbacks"
334
+ ]);
335
+ if (maybeCallbacks) {
336
+ operation.callbacks = maybeCallbacks;
337
+ }
338
+ return operation;
339
+ };
340
+ const createPathItem = (pathItem, registry, path) => {
341
+ const pathItemObject = {};
342
+ const { id, ...rest } = pathItem;
343
+ for (const [key, value] of Object.entries(rest)) {
344
+ if (key === "get" || key === "put" || key === "post" || key === "delete" || key === "options" || key === "head" || key === "patch" || key === "trace") {
345
+ pathItemObject[key] = createOperation(
346
+ value,
347
+ registry,
348
+ [...path, key]
349
+ );
350
+ continue;
351
+ }
352
+ if (key === "parameters") {
353
+ pathItemObject[key] = createManualParameters(
354
+ value,
355
+ {
356
+ registry,
357
+ io: "input"
358
+ },
359
+ [...path, key]
360
+ );
361
+ continue;
362
+ }
363
+ pathItemObject[key] = value;
364
+ }
365
+ if (id) {
366
+ const ref = {
367
+ $ref: `#/components/pathItems/${id}`
368
+ };
369
+ registry.pathItems.ids.set(id, pathItemObject);
370
+ registry.pathItems.seen.set(pathItem, ref);
371
+ return ref;
372
+ }
373
+ registry.pathItems.seen.set(pathItem, pathItemObject);
374
+ return pathItemObject;
375
+ };
376
+ const createPaths = (paths, registry, path) => {
377
+ if (!paths) {
378
+ return void 0;
379
+ }
380
+ const pathsObject = {};
381
+ for (const [singlePath, pathItemObject] of Object.entries(paths)) {
382
+ if (isISpecificationExtension(singlePath)) {
383
+ pathsObject[singlePath] = pathItemObject;
384
+ continue;
385
+ }
386
+ pathsObject[singlePath] = createPathItem(pathItemObject, registry, [
387
+ ...path,
388
+ singlePath
389
+ ]);
390
+ }
391
+ return pathsObject;
392
+ };
393
+ const createCallback = (callbackObject, registry, path) => {
394
+ const seenCallback = registry.callbacks.seen.get(callbackObject);
395
+ if (seenCallback) {
396
+ return seenCallback;
397
+ }
398
+ const { id, ...rest } = callbackObject;
399
+ const callback = {};
400
+ for (const [name, pathItem] of Object.entries(rest)) {
401
+ if (isISpecificationExtension(name)) {
402
+ callback[name] = pathItem;
403
+ continue;
404
+ }
405
+ callback[name] = createPathItem(
406
+ pathItem,
407
+ registry,
408
+ [...path, name]
409
+ );
410
+ }
411
+ if (id) {
412
+ const ref = {
413
+ $ref: `#/components/callbacks/${id}`
414
+ };
415
+ registry.callbacks.ids.set(id, callback);
416
+ registry.callbacks.seen.set(callbackObject, ref);
417
+ return ref;
418
+ }
419
+ registry.callbacks.seen.set(callbackObject, callback);
420
+ return callback;
421
+ };
422
+ const createCallbacks = (callbacks, registry, path) => {
423
+ if (!callbacks) {
424
+ return void 0;
425
+ }
426
+ const callbacksObject = {};
427
+ for (const [name, value] of Object.entries(callbacks)) {
428
+ if (isISpecificationExtension(name)) {
429
+ callbacksObject[name] = value;
430
+ continue;
431
+ }
432
+ callbacksObject[name] = createCallback(
433
+ value,
434
+ registry,
435
+ [...path, name]
436
+ );
437
+ }
438
+ return callbacksObject;
439
+ };
440
+ const override = (ctx) => {
441
+ var _a;
442
+ const def = ctx.zodSchema._zod.def;
443
+ switch (def.type) {
444
+ case "bigint": {
445
+ ctx.jsonSchema.type = "integer";
446
+ ctx.jsonSchema.format = "int64";
447
+ break;
448
+ }
449
+ case "union": {
450
+ if ("discriminator" in def && typeof def.discriminator === "string") {
451
+ ctx.jsonSchema.oneOf = ctx.jsonSchema.anyOf;
452
+ delete ctx.jsonSchema.anyOf;
453
+ ctx.jsonSchema.type = "object";
454
+ ctx.jsonSchema.discriminator = {
455
+ propertyName: def.discriminator
456
+ };
457
+ const mapping = {};
458
+ for (const [index, obj] of Object.entries(
459
+ ctx.jsonSchema.oneOf
460
+ )) {
461
+ const ref = obj.$ref;
462
+ if (!ref) {
463
+ return;
464
+ }
465
+ const discriminatorValues = (_a = def.options[Number(index)]._zod.propValues) == null ? void 0 : _a[def.discriminator];
466
+ if (!(discriminatorValues == null ? void 0 : discriminatorValues.size)) {
467
+ return;
468
+ }
469
+ for (const value of [...discriminatorValues ?? []]) {
470
+ if (typeof value !== "string") {
471
+ return;
472
+ }
473
+ mapping[value] = ref;
474
+ }
475
+ }
476
+ ctx.jsonSchema.discriminator.mapping = mapping;
477
+ }
478
+ const meta = ctx.zodSchema.meta();
479
+ if (typeof (meta == null ? void 0 : meta.unionOneOf) === "boolean") {
480
+ if (meta.unionOneOf) {
481
+ ctx.jsonSchema.oneOf = ctx.jsonSchema.anyOf;
482
+ delete ctx.jsonSchema.anyOf;
483
+ }
484
+ delete ctx.jsonSchema.unionOneOf;
485
+ }
486
+ break;
487
+ }
488
+ case "date": {
489
+ ctx.jsonSchema.type = "string";
490
+ break;
491
+ }
492
+ case "literal": {
493
+ if (def.values.includes(void 0)) {
494
+ break;
495
+ }
496
+ break;
497
+ }
498
+ }
499
+ };
500
+ const validate = (ctx, opts) => {
501
+ var _a;
502
+ if (Object.keys(ctx.jsonSchema).length) {
503
+ return;
504
+ }
505
+ const def = ctx.zodSchema._zod.def;
506
+ if ((_a = opts.allowEmptySchema) == null ? void 0 : _a[def.type]) {
507
+ return;
508
+ }
509
+ switch (def.type) {
510
+ case "any": {
511
+ return;
512
+ }
513
+ case "unknown": {
514
+ return;
515
+ }
516
+ case "pipe": {
517
+ if (ctx.io === "output") {
518
+ throw new Error(
519
+ "Zod transform schemas are not supported in output schemas. Please use `.overwrite()` or wrap the schema in a `.pipe()`"
520
+ );
521
+ }
522
+ return;
523
+ }
524
+ case "transform": {
525
+ if (ctx.io === "output") {
526
+ return;
527
+ }
528
+ break;
529
+ }
530
+ case "literal": {
531
+ if (def.values.includes(void 0)) {
532
+ throw new Error(
533
+ "Zod literal schemas cannot include `undefined` as a value. Please use `z.undefined()` or `.optional()` instead."
534
+ );
535
+ }
536
+ return;
537
+ }
538
+ }
539
+ throw new Error(
540
+ `Zod schema of type \`${def.type}\` cannot be represented in OpenAPI. Please assign it metadata with \`.meta()\``
541
+ );
542
+ };
543
+ const renameComponents = (components, outputIds, ctx) => {
544
+ const componentsToRename = /* @__PURE__ */ new Map();
545
+ const componentDependencies = /* @__PURE__ */ new Map();
546
+ const stringifiedComponents = /* @__PURE__ */ new Map();
547
+ for (const [key, value] of Object.entries(components)) {
548
+ const stringified = JSON.stringify(value);
549
+ const matches = stringified.matchAll(/"#\/components\/schemas\/([^"]+)"/g);
550
+ const dependencies = /* @__PURE__ */ new Set();
551
+ for (const match of matches) {
552
+ const dep = match[1];
553
+ if (dep !== key) {
554
+ dependencies.add(dep);
555
+ }
556
+ }
557
+ stringifiedComponents.set(key, stringified);
558
+ componentDependencies.set(key, {
559
+ dependencies
560
+ });
561
+ }
562
+ for (const [key] of stringifiedComponents) {
563
+ const registeredComponent = ctx.registry.schemas.ids.get(key);
564
+ if (!registeredComponent) {
565
+ continue;
566
+ }
567
+ if (isDependencyPure(
568
+ componentDependencies,
569
+ stringifiedComponents,
570
+ ctx.registry,
571
+ key
572
+ )) {
573
+ continue;
574
+ }
575
+ const newName = outputIds.get(key) ?? `${key}Output`;
576
+ componentsToRename.set(key, newName);
577
+ components[newName] = components[key];
578
+ delete components[key];
579
+ continue;
580
+ }
581
+ return componentsToRename;
582
+ };
583
+ const isDependencyPure = (componentDependencies, stringifiedComponents, registry, key, visited = /* @__PURE__ */ new Set()) => {
584
+ if (visited.has(key)) {
585
+ return true;
586
+ }
587
+ const dependencies = componentDependencies.get(key);
588
+ if (dependencies.pure !== void 0) {
589
+ return dependencies.pure;
590
+ }
591
+ const stringified = stringifiedComponents.get(key);
592
+ const component = registry.schemas.ids.get(key);
593
+ if (component && stringified !== JSON.stringify(component)) {
594
+ dependencies.pure = false;
595
+ return false;
596
+ }
597
+ visited.add(key);
598
+ const result = [...dependencies.dependencies].every(
599
+ (dep) => isDependencyPure(
600
+ componentDependencies,
601
+ stringifiedComponents,
602
+ registry,
603
+ dep,
604
+ new Set(visited)
605
+ )
606
+ );
607
+ dependencies.pure = result;
608
+ return result;
609
+ };
610
+ const deleteZodOpenApiMeta = (jsonSchema) => {
611
+ delete jsonSchema.param;
612
+ delete jsonSchema.header;
613
+ delete jsonSchema.unusedIO;
614
+ delete jsonSchema.override;
615
+ delete jsonSchema.outputId;
616
+ };
617
+ const createSchema = (schema, ctx = {
618
+ registry: createRegistry(),
619
+ io: "output",
620
+ opts: {}
621
+ }) => {
622
+ ctx.registry ?? (ctx.registry = createRegistry());
623
+ ctx.opts ?? (ctx.opts = {});
624
+ ctx.io ?? (ctx.io = "output");
625
+ const registrySchemas = Object.fromEntries(
626
+ ctx.registry.schemas[ctx.io].schemas
627
+ );
628
+ const schemas = {
629
+ zodOpenApiCreateSchema: { zodType: schema }
630
+ };
631
+ Object.assign(schemas, registrySchemas);
632
+ const jsonSchemas = createSchemas(schemas, {
633
+ registry: ctx.registry,
634
+ io: ctx.io,
635
+ opts: ctx.opts
636
+ });
637
+ return {
638
+ schema: jsonSchemas.schemas.zodOpenApiCreateSchema,
639
+ components: jsonSchemas.components
640
+ };
641
+ };
642
+ const createSchemas = (schemas, {
643
+ registry,
644
+ io,
645
+ opts
646
+ }) => {
647
+ var _a, _b, _c, _d, _e, _f;
648
+ const schemaRegistry = v4.registry();
649
+ const globalsInSchemas = /* @__PURE__ */ new Map();
650
+ for (const [name, { zodType }] of Object.entries(schemas)) {
651
+ const id = (_a = v4.globalRegistry.get(zodType)) == null ? void 0 : _a.id;
652
+ if (id) {
653
+ globalsInSchemas.set(name, id);
654
+ }
655
+ schemaRegistry.add(zodType, { id: name });
656
+ }
657
+ const outputIds = /* @__PURE__ */ new Map();
658
+ const jsonSchema = v4.toJSONSchema(schemaRegistry, {
659
+ override(ctx) {
660
+ const meta = ctx.zodSchema.meta();
661
+ if ((meta == null ? void 0 : meta.outputId) && (meta == null ? void 0 : meta.id)) {
662
+ outputIds.set(meta.id, meta.outputId);
663
+ }
664
+ if (ctx.jsonSchema.$ref) {
665
+ return;
666
+ }
667
+ const enrichedContext = { ...ctx, io };
668
+ override(enrichedContext);
669
+ if (typeof opts.override === "function") {
670
+ opts.override(enrichedContext);
671
+ }
672
+ if (typeof (meta == null ? void 0 : meta.override) === "function") {
673
+ meta.override(enrichedContext);
674
+ delete ctx.jsonSchema.override;
675
+ }
676
+ if (typeof (meta == null ? void 0 : meta.override) === "object" && meta.override !== null) {
677
+ Object.assign(ctx.jsonSchema, meta.override);
678
+ delete ctx.jsonSchema.override;
679
+ }
680
+ delete ctx.jsonSchema.$schema;
681
+ delete ctx.jsonSchema.id;
682
+ deleteZodOpenApiMeta(ctx.jsonSchema);
683
+ validate(enrichedContext, opts);
684
+ },
685
+ io,
686
+ unrepresentable: "any",
687
+ uri: (id) => `#/components/schemas/${id}`
688
+ });
689
+ const sharedDefs = ((_b = jsonSchema.schemas.__shared) == null ? void 0 : _b.$defs) ?? {};
690
+ (_c = jsonSchema.schemas).__shared ?? (_c.__shared = { $defs: sharedDefs });
691
+ const componentsToReplace = /* @__PURE__ */ new Map();
692
+ for (const [key, value] of Object.entries(sharedDefs)) {
693
+ if (/^schema\d+$/.exec(key)) {
694
+ const componentName = `__schema${registry.schemas.dynamicSchemaCount++}`;
695
+ componentsToReplace.set(`__shared#/$defs/${key}`, componentName);
696
+ delete sharedDefs[key];
697
+ sharedDefs[componentName] = value;
698
+ continue;
699
+ }
700
+ componentsToReplace.set(`__shared#/$defs/${key}`, key);
701
+ }
702
+ for (const value of Object.values(jsonSchema.schemas)) {
703
+ delete value.$schema;
704
+ delete value.id;
705
+ }
706
+ const dynamicComponent = /* @__PURE__ */ new Map();
707
+ const patched = JSON.stringify(jsonSchema).replace(
708
+ /"#\/components\/schemas\/([^"]+)"/g,
709
+ (_, match) => {
710
+ const replacement = componentsToReplace.get(match);
711
+ if (replacement) {
712
+ return `"#/components/schemas/${replacement}"`;
713
+ }
714
+ const component = registry.schemas.ids.get(match);
715
+ if (component) {
716
+ return `"#/components/schemas/${match}`;
717
+ }
718
+ const globalInSchema = globalsInSchemas.get(match);
719
+ if (globalInSchema) {
720
+ componentsToReplace.set(match, globalInSchema);
721
+ dynamicComponent.set(match, globalInSchema);
722
+ return `"#/components/schemas/${globalInSchema}"`;
723
+ }
724
+ const manualSchema = registry.schemas.manual.get(match);
725
+ if (manualSchema) {
726
+ componentsToReplace.set(match, manualSchema.key);
727
+ dynamicComponent.set(match, manualSchema.key);
728
+ manualSchema.io[io].used = true;
729
+ return `"#/components/schemas/${manualSchema.key}"`;
730
+ }
731
+ const componentName = `__schema${registry.schemas.dynamicSchemaCount++}`;
732
+ componentsToReplace.set(match, componentName);
733
+ dynamicComponent.set(match, componentName);
734
+ return `"#/components/schemas/${componentName}"`;
735
+ }
736
+ );
737
+ const patchedJsonSchema = JSON.parse(patched);
738
+ const components = ((_d = patchedJsonSchema.schemas.__shared) == null ? void 0 : _d.$defs) ?? {};
739
+ (_e = patchedJsonSchema.schemas).__shared ?? (_e.__shared = { $defs: components });
740
+ for (const [key, value] of registry.schemas.manual) {
741
+ if (value.io[io].used) {
742
+ dynamicComponent.set(key, value.key);
743
+ }
744
+ }
745
+ for (const [key, value] of globalsInSchemas) {
746
+ dynamicComponent.set(key, value);
747
+ }
748
+ for (const [key, value] of dynamicComponent) {
749
+ const component = patchedJsonSchema.schemas[key];
750
+ patchedJsonSchema.schemas[key] = {
751
+ $ref: `#/components/schemas/${value}`
752
+ };
753
+ components[value] = component;
754
+ }
755
+ const renamedComponents = renameComponents(components, outputIds, {
756
+ registry
757
+ });
758
+ if (renamedComponents.size === 0) {
759
+ delete patchedJsonSchema.schemas.__shared;
760
+ return {
761
+ schemas: patchedJsonSchema.schemas,
762
+ components
763
+ };
764
+ }
765
+ const renamedStringified = JSON.stringify(patchedJsonSchema).replace(
766
+ /"#\/components\/schemas\/([^"]+)"/g,
767
+ (_, match) => {
768
+ const newName = renamedComponents.get(match);
769
+ if (newName) {
770
+ return `"#/components/schemas/${newName}"`;
771
+ }
772
+ return `"#/components/schemas/${match}"`;
773
+ }
774
+ );
775
+ const renamedJsonSchema = JSON.parse(renamedStringified);
776
+ const renamedJsonSchemaComponents = ((_f = renamedJsonSchema.schemas.__shared) == null ? void 0 : _f.$defs) ?? {};
777
+ delete renamedJsonSchema.schemas.__shared;
778
+ return {
779
+ schemas: renamedJsonSchema.schemas,
780
+ components: renamedJsonSchemaComponents
781
+ };
782
+ };
783
+ const createRegistry = (components) => {
784
+ const registry = {
785
+ schemas: {
786
+ dynamicSchemaCount: 0,
787
+ input: {
788
+ seen: /* @__PURE__ */ new WeakMap(),
789
+ schemas: /* @__PURE__ */ new Map()
790
+ },
791
+ output: {
792
+ seen: /* @__PURE__ */ new WeakMap(),
793
+ schemas: /* @__PURE__ */ new Map()
794
+ },
795
+ ids: /* @__PURE__ */ new Map(),
796
+ manual: /* @__PURE__ */ new Map(),
797
+ setSchema: (key, schema, io) => {
798
+ const seenSchema = registry.schemas[io].seen.get(schema);
799
+ if (seenSchema) {
800
+ if (seenSchema.type === "manual") {
801
+ const manualSchema = registry.schemas.manual.get(seenSchema.id);
802
+ if (!manualSchema) {
803
+ throw new Error(
804
+ `Manual schema "${key}" not found in registry for ${io} IO.`
805
+ );
806
+ }
807
+ manualSchema.io[io].used = true;
808
+ }
809
+ return seenSchema.schemaObject;
810
+ }
811
+ const schemaObject = {};
812
+ registry.schemas[io].schemas.set(key, {
813
+ schemaObject,
814
+ zodType: schema
815
+ });
816
+ registry.schemas[io].seen.set(schema, { type: "schema", schemaObject });
817
+ return schemaObject;
818
+ }
819
+ },
820
+ headers: {
821
+ ids: /* @__PURE__ */ new Map(),
822
+ seen: /* @__PURE__ */ new WeakMap()
823
+ },
824
+ requestBodies: {
825
+ ids: /* @__PURE__ */ new Map(),
826
+ seen: /* @__PURE__ */ new WeakMap()
827
+ },
828
+ responses: {
829
+ ids: /* @__PURE__ */ new Map(),
830
+ seen: /* @__PURE__ */ new WeakMap()
831
+ },
832
+ parameters: {
833
+ ids: /* @__PURE__ */ new Map(),
834
+ seen: /* @__PURE__ */ new WeakMap()
835
+ },
836
+ callbacks: {
837
+ ids: /* @__PURE__ */ new Map(),
838
+ seen: /* @__PURE__ */ new WeakMap()
839
+ },
840
+ pathItems: {
841
+ ids: /* @__PURE__ */ new Map(),
842
+ seen: /* @__PURE__ */ new WeakMap()
843
+ }
844
+ };
845
+ registerSchemas(components == null ? void 0 : components.schemas, registry);
846
+ registerParameters(components == null ? void 0 : components.parameters, registry);
847
+ registerHeaders(components == null ? void 0 : components.headers, registry);
848
+ registerResponses(components == null ? void 0 : components.responses, registry);
849
+ registerPathItems(components == null ? void 0 : components.pathItems, registry);
850
+ registerRequestBodies(components == null ? void 0 : components.requestBodies, registry);
851
+ registerCallbacks(components == null ? void 0 : components.callbacks, registry);
852
+ return registry;
853
+ };
854
+ const registerSchemas = (schemas, registry) => {
855
+ if (!schemas) {
856
+ return;
857
+ }
858
+ for (const [key, schema] of Object.entries(schemas)) {
859
+ if (registry.schemas.ids.has(key)) {
860
+ throw new Error(`Schema "${key}" is already registered`);
861
+ }
862
+ if (isAnyZodType(schema)) {
863
+ const inputSchemaObject = {};
864
+ const outputSchemaObject = {};
865
+ const identifier = `components > schemas > ${key}`;
866
+ registry.schemas.input.schemas.set(identifier, {
867
+ zodType: schema,
868
+ schemaObject: inputSchemaObject
869
+ });
870
+ registry.schemas.input.seen.set(schema, {
871
+ type: "manual",
872
+ schemaObject: inputSchemaObject,
873
+ id: identifier
874
+ });
875
+ registry.schemas.output.schemas.set(identifier, {
876
+ zodType: schema,
877
+ schemaObject: outputSchemaObject
878
+ });
879
+ registry.schemas.output.seen.set(schema, {
880
+ type: "manual",
881
+ schemaObject: outputSchemaObject,
882
+ id: identifier
883
+ });
884
+ registry.schemas.manual.set(identifier, {
885
+ key,
886
+ io: {
887
+ input: {
888
+ schemaObject: inputSchemaObject
889
+ },
890
+ output: {
891
+ schemaObject: outputSchemaObject
892
+ }
893
+ },
894
+ zodType: schema
895
+ });
896
+ continue;
897
+ }
898
+ registry.schemas.ids.set(key, schema);
899
+ }
900
+ };
901
+ const registerParameters = (parameters, registry) => {
902
+ if (!parameters) {
903
+ return;
904
+ }
905
+ for (const [key, schema] of Object.entries(parameters)) {
906
+ if (registry.parameters.ids.has(key)) {
907
+ throw new Error(`Parameter "${key}" is already registered`);
908
+ }
909
+ if (isAnyZodType(schema)) {
910
+ const path = ["components", "parameters", key];
911
+ const paramObject = createParameter(
912
+ schema,
913
+ void 0,
914
+ {
915
+ registry,
916
+ io: "input"
917
+ },
918
+ path
919
+ );
920
+ registry.parameters.ids.set(key, paramObject);
921
+ registry.parameters.seen.set(schema, paramObject);
922
+ continue;
923
+ }
924
+ registry.parameters.ids.set(key, schema);
925
+ }
926
+ };
927
+ const registerHeaders = (headers, registry) => {
928
+ if (!headers) {
929
+ return;
930
+ }
931
+ for (const [key, schema] of Object.entries(headers)) {
932
+ if (registry.headers.ids.has(key)) {
933
+ throw new Error(`Header "${key}" is already registered`);
934
+ }
935
+ if (isAnyZodType(schema)) {
936
+ const path = ["components", "headers", key];
937
+ const headerObject = createHeader(
938
+ schema,
939
+ {
940
+ registry,
941
+ io: "output"
942
+ },
943
+ path
944
+ );
945
+ registry.headers.ids.set(key, headerObject);
946
+ registry.headers.seen.set(schema, headerObject);
947
+ continue;
948
+ }
949
+ registry.headers.ids.set(key, schema);
950
+ }
951
+ };
952
+ const registerResponses = (responses, registry) => {
953
+ if (!responses) {
954
+ return;
955
+ }
956
+ for (const [key, schema] of Object.entries(responses)) {
957
+ const path = ["components", "responses", key];
958
+ if (registry.responses.ids.has(key)) {
959
+ throw new Error(`Response "${key}" is already registered`);
960
+ }
961
+ const responseObject = createResponse(
962
+ schema,
963
+ {
964
+ registry,
965
+ io: "output"
966
+ },
967
+ path
968
+ );
969
+ registry.responses.ids.set(key, responseObject);
970
+ registry.responses.seen.set(schema, responseObject);
971
+ }
972
+ };
973
+ const registerRequestBodies = (requestBodies, registry) => {
974
+ if (!requestBodies) {
975
+ return;
976
+ }
977
+ for (const [key, schema] of Object.entries(requestBodies)) {
978
+ if (registry.requestBodies.ids.has(key)) {
979
+ throw new Error(`RequestBody "${key}" is already registered`);
980
+ }
981
+ if (isAnyZodType(schema)) {
982
+ const path = ["components", "requestBodies", key];
983
+ const requestBodyObject = createRequestBody(
984
+ schema,
985
+ {
986
+ registry,
987
+ io: "input"
988
+ },
989
+ path
990
+ );
991
+ registry.requestBodies.ids.set(key, requestBodyObject);
992
+ continue;
993
+ }
994
+ registry.requestBodies.ids.set(key, schema);
995
+ }
996
+ };
997
+ const registerCallbacks = (callbacks, registry) => {
998
+ if (!callbacks) {
999
+ return;
1000
+ }
1001
+ for (const [key, schema] of Object.entries(callbacks)) {
1002
+ if (registry.callbacks.ids.has(key)) {
1003
+ throw new Error(`Callback "${key}" is already registered`);
1004
+ }
1005
+ const path = ["components", "callbacks", key];
1006
+ const callbackObject = createCallback(schema, registry, path);
1007
+ registry.callbacks.ids.set(key, callbackObject);
1008
+ registry.callbacks.seen.set(schema, callbackObject);
1009
+ }
1010
+ };
1011
+ const registerPathItems = (pathItems, registry) => {
1012
+ if (!pathItems) {
1013
+ return;
1014
+ }
1015
+ for (const [key, schema] of Object.entries(pathItems)) {
1016
+ if (registry.pathItems.ids.has(key)) {
1017
+ throw new Error(`PathItem "${key}" is already registered`);
1018
+ }
1019
+ const path = ["components", "pathItems", key];
1020
+ const pathItemObject = createPathItem(schema, registry, path);
1021
+ registry.pathItems.ids.set(key, pathItemObject);
1022
+ registry.pathItems.seen.set(schema, pathItemObject);
1023
+ continue;
1024
+ }
1025
+ };
1026
+ const createIOSchemas = (ctx) => {
1027
+ const { schemas, components } = createSchemas(
1028
+ Object.fromEntries(ctx.registry.schemas[ctx.io].schemas),
1029
+ ctx
1030
+ );
1031
+ for (const [key, schema] of Object.entries(components)) {
1032
+ ctx.registry.schemas.ids.set(key, schema);
1033
+ }
1034
+ for (const [key, schema] of Object.entries(schemas)) {
1035
+ const ioSchema = ctx.registry.schemas[ctx.io].schemas.get(key);
1036
+ if (ioSchema) {
1037
+ Object.assign(ioSchema.schemaObject, schema);
1038
+ }
1039
+ }
1040
+ };
1041
+ const createManualSchemas = (registry) => {
1042
+ var _a;
1043
+ for (const [, value] of registry.schemas.manual) {
1044
+ if (!value.io.input.used && !value.io.output.used) {
1045
+ const io = ((_a = core.globalRegistry.get(value.zodType)) == null ? void 0 : _a.unusedIO) ?? "output";
1046
+ const schema = value.io[io].schemaObject;
1047
+ registry.schemas.ids.set(value.key, schema);
1048
+ }
1049
+ }
1050
+ };
1051
+ const createComponents = (registry, opts) => {
1052
+ createIOSchemas({ registry, io: "input", opts });
1053
+ createIOSchemas({ registry, io: "output", opts });
1054
+ createManualSchemas(registry);
1055
+ const components = {};
1056
+ if (registry.schemas.ids.size > 0) {
1057
+ components.schemas = Object.fromEntries(registry.schemas.ids);
1058
+ }
1059
+ if (registry.headers.ids.size > 0) {
1060
+ components.headers = Object.fromEntries(registry.headers.ids);
1061
+ }
1062
+ if (registry.requestBodies.ids.size > 0) {
1063
+ components.requestBodies = Object.fromEntries(registry.requestBodies.ids);
1064
+ }
1065
+ if (registry.responses.ids.size > 0) {
1066
+ components.responses = Object.fromEntries(registry.responses.ids);
1067
+ }
1068
+ if (registry.parameters.ids.size > 0) {
1069
+ components.parameters = Object.fromEntries(registry.parameters.ids);
1070
+ }
1071
+ if (registry.callbacks.ids.size > 0) {
1072
+ components.callbacks = Object.fromEntries(registry.callbacks.ids);
1073
+ }
1074
+ if (registry.pathItems.ids.size > 0) {
1075
+ components.pathItems = Object.fromEntries(registry.pathItems.ids);
1076
+ }
1077
+ return components;
1078
+ };
1079
+ exports.createComponents = createComponents;
1080
+ exports.createMediaTypeObject = createMediaTypeObject;
1081
+ exports.createParameter = createParameter;
1082
+ exports.createPaths = createPaths;
1083
+ exports.createRegistry = createRegistry;
1084
+ exports.createSchema = createSchema;
1085
+ exports.unwrapZodObject = unwrapZodObject;