zod-openapi 5.0.0-beta.0 → 5.0.0-beta.10

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,747 @@
1
+ import { globalRegistry } from "zod/v4/core";
2
+ import { object, registry, toJSONSchema } from "zod/v4";
3
+
4
+ //#region src/zod.ts
5
+ const isAnyZodType = (schema) => typeof schema === "object" && schema !== null && "_zod" in schema;
6
+
7
+ //#endregion
8
+ //#region src/create/content.ts
9
+ const createMediaTypeObject = (mediaTypeObject, ctx, path) => {
10
+ if (isAnyZodType(mediaTypeObject.schema)) {
11
+ const schemaObject = ctx.registry.addSchema(mediaTypeObject.schema, [...path, "schema"], { io: ctx.io });
12
+ return {
13
+ ...mediaTypeObject,
14
+ schema: schemaObject
15
+ };
16
+ }
17
+ return mediaTypeObject;
18
+ };
19
+ const createContent = (content, ctx, path) => {
20
+ const contentObject = {};
21
+ for (const [mediaType, mediaTypeObject] of Object.entries(content)) if (mediaTypeObject) contentObject[mediaType] = createMediaTypeObject(mediaTypeObject, ctx, [...path, mediaType]);
22
+ return contentObject;
23
+ };
24
+
25
+ //#endregion
26
+ //#region src/create/object.ts
27
+ const unwrapZodObject = (zodType, io, path) => {
28
+ const def = zodType._zod.def;
29
+ switch (def.type) {
30
+ case "object": return zodType;
31
+ case "lazy": return unwrapZodObject(def.getter(), io, path);
32
+ case "pipe": {
33
+ if (io === "input") return unwrapZodObject(def.in, io, path);
34
+ return unwrapZodObject(def.out, io, path);
35
+ }
36
+ }
37
+ throw new Error(`Failed to unwrap ZodObject from type: ${zodType._zod.def.type} at ${path.join(" > ")}`);
38
+ };
39
+ const isRequired = (zodType, io) => {
40
+ if (io === "input") return zodType._zod.optin === void 0;
41
+ return zodType._zod.optout === void 0;
42
+ };
43
+
44
+ //#endregion
45
+ //#region src/create/headers.ts
46
+ const createHeaders = (headers, registry$1, path) => {
47
+ if (!headers) return void 0;
48
+ if (isAnyZodType(headers)) {
49
+ const zodObject = unwrapZodObject(headers, "output", path);
50
+ const headersObject = {};
51
+ for (const [key, zodSchema] of Object.entries(zodObject._zod.def.shape)) {
52
+ const header = registry$1.addHeader(zodSchema, [...path, key]);
53
+ headersObject[key] = header;
54
+ }
55
+ return headersObject;
56
+ }
57
+ return headers;
58
+ };
59
+
60
+ //#endregion
61
+ //#region src/create/parameters.ts
62
+ const createManualParameters = (parameters, registry$1, path) => {
63
+ if (!parameters) return void 0;
64
+ const parameterObjects = [];
65
+ for (const parameter of parameters) {
66
+ if (isAnyZodType(parameter)) {
67
+ const paramObject = registry$1.addParameter(parameter, [...path, "parameters"]);
68
+ parameterObjects.push(paramObject);
69
+ continue;
70
+ }
71
+ parameterObjects.push(parameter);
72
+ }
73
+ return parameterObjects;
74
+ };
75
+ const createParameters = (requestParams, registry$1, path) => {
76
+ if (!requestParams) return void 0;
77
+ const parameterObjects = [];
78
+ for (const [location, schema] of Object.entries(requestParams ?? {})) {
79
+ const zodObject = unwrapZodObject(schema, "input", path);
80
+ for (const [name, zodSchema] of Object.entries(zodObject._zod.def.shape)) {
81
+ const paramObject = registry$1.addParameter(zodSchema, [
82
+ ...path,
83
+ location,
84
+ name
85
+ ], { location: {
86
+ in: location,
87
+ name
88
+ } });
89
+ parameterObjects.push(paramObject);
90
+ }
91
+ }
92
+ return parameterObjects;
93
+ };
94
+
95
+ //#endregion
96
+ //#region src/create/specificationExtension.ts
97
+ const isISpecificationExtension = (key) => key.startsWith("x-");
98
+
99
+ //#endregion
100
+ //#region src/create/callbacks.ts
101
+ const createCallbacks = (callbacks, registry$1, path) => {
102
+ if (!callbacks) return void 0;
103
+ const callbacksObject = {};
104
+ for (const [name, value] of Object.entries(callbacks)) {
105
+ if (isISpecificationExtension(name)) {
106
+ callbacksObject[name] = value;
107
+ continue;
108
+ }
109
+ callbacksObject[name] = registry$1.addCallback(value, [...path, name]);
110
+ }
111
+ return callbacksObject;
112
+ };
113
+
114
+ //#endregion
115
+ //#region src/create/responses.ts
116
+ const createResponses = (responses, registry$1, path) => {
117
+ if (!responses) return void 0;
118
+ const responsesObject = {};
119
+ for (const [statusCode, response] of Object.entries(responses)) {
120
+ if (!response) continue;
121
+ if (isISpecificationExtension(statusCode)) {
122
+ responsesObject[statusCode] = response;
123
+ continue;
124
+ }
125
+ if ("$ref" in response) {
126
+ responsesObject[statusCode] = response;
127
+ continue;
128
+ }
129
+ const responseObject = registry$1.addResponse(response, [...path, statusCode]);
130
+ responsesObject[statusCode] = responseObject;
131
+ }
132
+ return responsesObject;
133
+ };
134
+
135
+ //#endregion
136
+ //#region src/create/paths.ts
137
+ const createOperation = (operation, registry$1, path) => {
138
+ const { parameters, requestParams, requestBody, responses, callbacks,...rest } = operation;
139
+ const operationObject = rest;
140
+ const maybeManualParameters = createManualParameters(parameters, registry$1, [...path, "parameters"]);
141
+ const maybeRequestParams = createParameters(requestParams, registry$1, [...path, "requestParams"]);
142
+ if (maybeRequestParams || maybeManualParameters) operationObject.parameters = [...maybeRequestParams ?? [], ...maybeManualParameters ?? []];
143
+ const maybeRequestBody = requestBody && registry$1.addRequestBody(requestBody, path);
144
+ if (maybeRequestBody) operationObject.requestBody = maybeRequestBody;
145
+ const maybeResponses = createResponses(responses, registry$1, [...path, "responses"]);
146
+ if (maybeResponses) operationObject.responses = maybeResponses;
147
+ const maybeCallbacks = createCallbacks(callbacks, registry$1, [...path, "callbacks"]);
148
+ if (maybeCallbacks) operationObject.callbacks = maybeCallbacks;
149
+ return operationObject;
150
+ };
151
+ const createPaths = (paths, registry$1, path) => {
152
+ if (!paths) return void 0;
153
+ const pathsObject = {};
154
+ for (const [singlePath, pathItemObject] of Object.entries(paths)) {
155
+ if (isISpecificationExtension(singlePath)) {
156
+ pathsObject[singlePath] = pathItemObject;
157
+ continue;
158
+ }
159
+ pathsObject[singlePath] = registry$1.addPathItem(pathItemObject, [...path, singlePath]);
160
+ }
161
+ return pathsObject;
162
+ };
163
+
164
+ //#endregion
165
+ //#region src/create/schema/override.ts
166
+ const override = (ctx) => {
167
+ const def = ctx.zodSchema._zod.def;
168
+ switch (def.type) {
169
+ case "bigint": {
170
+ ctx.jsonSchema.type = "integer";
171
+ ctx.jsonSchema.format = "int64";
172
+ break;
173
+ }
174
+ case "union": {
175
+ if ("discriminator" in def && typeof def.discriminator === "string") {
176
+ ctx.jsonSchema.oneOf = ctx.jsonSchema.anyOf;
177
+ delete ctx.jsonSchema.anyOf;
178
+ ctx.jsonSchema.type = "object";
179
+ ctx.jsonSchema.discriminator = { propertyName: def.discriminator };
180
+ const mapping = {};
181
+ for (const [index, obj] of Object.entries(ctx.jsonSchema.oneOf)) {
182
+ const ref = obj.$ref;
183
+ if (!ref) return;
184
+ const discriminatorValues = def.options[Number(index)]._zod.propValues?.[def.discriminator];
185
+ if (!discriminatorValues?.size) return;
186
+ for (const value of [...discriminatorValues ?? []]) {
187
+ if (typeof value !== "string") return;
188
+ mapping[value] = ref;
189
+ }
190
+ }
191
+ ctx.jsonSchema.discriminator.mapping = mapping;
192
+ }
193
+ const meta = ctx.zodSchema.meta();
194
+ if (typeof meta?.unionOneOf === "boolean") {
195
+ if (meta.unionOneOf) {
196
+ ctx.jsonSchema.oneOf = ctx.jsonSchema.anyOf;
197
+ delete ctx.jsonSchema.anyOf;
198
+ }
199
+ delete ctx.jsonSchema.unionOneOf;
200
+ }
201
+ break;
202
+ }
203
+ case "date": {
204
+ ctx.jsonSchema.type = "string";
205
+ break;
206
+ }
207
+ case "literal": {
208
+ if (def.values.includes(void 0)) break;
209
+ break;
210
+ }
211
+ }
212
+ };
213
+ const validate = (ctx, opts) => {
214
+ if (Object.keys(ctx.jsonSchema).length) return;
215
+ const def = ctx.zodSchema._zod.def;
216
+ const allowEmptySchema = opts.allowEmptySchema?.[def.type];
217
+ if (allowEmptySchema === true || allowEmptySchema?.[ctx.io]) return;
218
+ switch (def.type) {
219
+ case "any": return;
220
+ case "unknown": return;
221
+ case "pipe": {
222
+ if (ctx.io === "output") throw new Error("Zod transform schemas are not supported in output schemas. Please use `.overwrite()` or wrap the schema in a `.pipe()`");
223
+ return;
224
+ }
225
+ case "transform": {
226
+ if (ctx.io === "output") return;
227
+ break;
228
+ }
229
+ case "literal": {
230
+ if (def.values.includes(void 0)) throw new Error("Zod literal schemas cannot include `undefined` as a value. Please use `z.undefined()` or `.optional()` instead.");
231
+ return;
232
+ }
233
+ }
234
+ throw new Error(`Zod schema of type \`${def.type}\` cannot be represented in OpenAPI. Please assign it metadata with \`.meta()\``);
235
+ };
236
+
237
+ //#endregion
238
+ //#region src/create/schema/rename.ts
239
+ const renameComponents = (components, outputIds, ctx) => {
240
+ const componentsToRename = /* @__PURE__ */ new Map();
241
+ if (ctx.io === "input") return componentsToRename;
242
+ const componentDependencies = /* @__PURE__ */ new Map();
243
+ const stringifiedComponents = /* @__PURE__ */ new Map();
244
+ for (const [key, value] of Object.entries(components)) {
245
+ const stringified = JSON.stringify(value);
246
+ const matches = stringified.matchAll(/"#\/components\/schemas\/([^"]+)"/g);
247
+ const dependencies = /* @__PURE__ */ new Set();
248
+ for (const match of matches) {
249
+ const dep = match[1];
250
+ if (dep !== key) dependencies.add(dep);
251
+ }
252
+ stringifiedComponents.set(key, stringified);
253
+ componentDependencies.set(key, { dependencies });
254
+ }
255
+ for (const [key] of stringifiedComponents) {
256
+ const registeredComponent = ctx.registry.components.schemas.ids.get(key);
257
+ if (!registeredComponent) continue;
258
+ if (isDependencyPure(componentDependencies, stringifiedComponents, ctx.registry, key)) continue;
259
+ const newName = outputIds.get(key) ?? `${key}Output`;
260
+ componentsToRename.set(key, newName);
261
+ components[newName] = components[key];
262
+ delete components[key];
263
+ continue;
264
+ }
265
+ return componentsToRename;
266
+ };
267
+ const isDependencyPure = (componentDependencies, stringifiedComponents, registry$1, key, visited = /* @__PURE__ */ new Set()) => {
268
+ if (visited.has(key)) return true;
269
+ const dependencies = componentDependencies.get(key);
270
+ if (dependencies.pure !== void 0) return dependencies.pure;
271
+ const stringified = stringifiedComponents.get(key);
272
+ const component = registry$1.components.schemas.ids.get(key);
273
+ if (component && stringified !== JSON.stringify(component)) {
274
+ dependencies.pure = false;
275
+ return false;
276
+ }
277
+ visited.add(key);
278
+ const result = [...dependencies.dependencies].every((dep) => isDependencyPure(componentDependencies, stringifiedComponents, registry$1, dep, new Set(visited)));
279
+ dependencies.pure = result;
280
+ return result;
281
+ };
282
+
283
+ //#endregion
284
+ //#region src/create/schema/schema.ts
285
+ const deleteZodOpenApiMeta = (jsonSchema) => {
286
+ delete jsonSchema.param;
287
+ delete jsonSchema.header;
288
+ delete jsonSchema.unusedIO;
289
+ delete jsonSchema.override;
290
+ delete jsonSchema.outputId;
291
+ };
292
+ const createSchema = (schema, ctx = {
293
+ registry: createRegistry(),
294
+ io: "output",
295
+ opts: {}
296
+ }) => {
297
+ ctx.registry ??= createRegistry();
298
+ ctx.opts ??= {};
299
+ ctx.io ??= "output";
300
+ const registrySchemas = Object.fromEntries(ctx.registry.components.schemas[ctx.io]);
301
+ const schemas = { zodOpenApiCreateSchema: { zodType: schema } };
302
+ Object.assign(schemas, registrySchemas);
303
+ const jsonSchemas = createSchemas(schemas, {
304
+ registry: ctx.registry,
305
+ io: ctx.io,
306
+ opts: ctx.opts
307
+ });
308
+ return {
309
+ schema: jsonSchemas.schemas.zodOpenApiCreateSchema,
310
+ components: jsonSchemas.components
311
+ };
312
+ };
313
+ const createSchemas = (schemas, ctx) => {
314
+ const entries = {};
315
+ for (const [name, { zodType }] of Object.entries(schemas)) entries[name] = zodType;
316
+ const zodRegistry = registry();
317
+ zodRegistry.add(object(entries), { id: "zodOpenApiCreateSchema" });
318
+ for (const [id, { zodType }] of ctx.registry.components.schemas.manual) zodRegistry.add(zodType, { id });
319
+ const outputIds = /* @__PURE__ */ new Map();
320
+ const jsonSchema = toJSONSchema(zodRegistry, {
321
+ override(context) {
322
+ const meta = context.zodSchema.meta();
323
+ if (meta?.outputId && meta?.id) outputIds.set(meta.id, meta.outputId);
324
+ if (context.jsonSchema.$ref) return;
325
+ const enrichedContext = {
326
+ ...context,
327
+ io: ctx.io
328
+ };
329
+ override(enrichedContext);
330
+ if (typeof ctx.opts.override === "function") ctx.opts.override(enrichedContext);
331
+ if (typeof meta?.override === "function") {
332
+ meta.override(enrichedContext);
333
+ delete context.jsonSchema.override;
334
+ }
335
+ if (typeof meta?.override === "object" && meta.override !== null) {
336
+ Object.assign(context.jsonSchema, meta.override);
337
+ delete context.jsonSchema.override;
338
+ }
339
+ delete context.jsonSchema.$schema;
340
+ delete context.jsonSchema.id;
341
+ deleteZodOpenApiMeta(context.jsonSchema);
342
+ validate(enrichedContext, ctx.opts);
343
+ },
344
+ io: ctx.io,
345
+ unrepresentable: "any",
346
+ reused: ctx.opts.reused,
347
+ cycles: ctx.opts.cycles,
348
+ uri: (id) => id === "__shared" ? `#ZOD_OPENAPI/${id}` : `#ZOD_OPENAPI/__shared#/$defs/${id}`
349
+ });
350
+ const components = jsonSchema.schemas.__shared?.$defs ?? {};
351
+ jsonSchema.schemas.__shared ??= { $defs: components };
352
+ const dynamicComponents = /* @__PURE__ */ new Map();
353
+ for (const [key, value] of Object.entries(components)) if (/^schema\d+$/.test(key)) {
354
+ const newName = `__schema${ctx.registry.components.schemas.dynamicSchemaCount++}`;
355
+ dynamicComponents.set(key, `"#/components/schemas/${newName}"`);
356
+ if (newName !== key) {
357
+ components[newName] = value;
358
+ delete components[key];
359
+ }
360
+ }
361
+ const manualUsed = {};
362
+ const parsedJsonSchema = JSON.parse(JSON.stringify(jsonSchema).replace(/"#ZOD_OPENAPI\/__shared#\/\$defs\/([^"]+)"/g, (_, match) => {
363
+ const dynamic = dynamicComponents.get(match);
364
+ if (dynamic) return dynamic;
365
+ const manualComponent = ctx.registry.components.schemas.manual.get(match);
366
+ if (manualComponent) manualUsed[match] = true;
367
+ return `"#/components/schemas/${match}"`;
368
+ }));
369
+ const parsedComponents = parsedJsonSchema.schemas.__shared?.$defs ?? {};
370
+ parsedJsonSchema.schemas.__shared ??= { $defs: parsedComponents };
371
+ for (const [key] of ctx.registry.components.schemas.manual) {
372
+ const manualComponent = parsedJsonSchema.schemas[key];
373
+ if (!manualComponent) continue;
374
+ delete manualComponent.$schema;
375
+ delete manualComponent.id;
376
+ if (manualUsed[key]) {
377
+ delete manualComponent.$schema;
378
+ delete manualComponent.id;
379
+ if (parsedComponents[key]) throw new Error(`Component "${key}" is already registered as a component in the registry`);
380
+ parsedComponents[key] = manualComponent;
381
+ }
382
+ }
383
+ const componentsToRename = renameComponents(parsedComponents, outputIds, ctx);
384
+ if (!componentsToRename.size) {
385
+ const parsedSchemas = parsedJsonSchema.schemas.zodOpenApiCreateSchema?.properties;
386
+ delete parsedJsonSchema.schemas.zodOpenApiCreateSchema;
387
+ delete parsedJsonSchema.schemas.__shared;
388
+ return {
389
+ schemas: parsedSchemas,
390
+ components: parsedComponents,
391
+ manual: parsedJsonSchema.schemas
392
+ };
393
+ }
394
+ const renamedJsonSchema = JSON.parse(JSON.stringify(parsedJsonSchema).replace(/"#\/components\/schemas\/([^"]+)"/g, (_, match) => {
395
+ const replacement = componentsToRename.get(match);
396
+ if (replacement) return `"#/components/schemas/${replacement}"`;
397
+ return `"#/components/schemas/${match}"`;
398
+ }));
399
+ const renamedSchemas = renamedJsonSchema.schemas.zodOpenApiCreateSchema?.properties;
400
+ const renamedComponents = renamedJsonSchema.schemas.__shared?.$defs ?? {};
401
+ delete renamedJsonSchema.schemas.zodOpenApiCreateSchema;
402
+ delete renamedJsonSchema.schemas.__shared;
403
+ return {
404
+ schemas: renamedSchemas,
405
+ components: renamedComponents,
406
+ manual: renamedJsonSchema.schemas
407
+ };
408
+ };
409
+
410
+ //#endregion
411
+ //#region src/create/components.ts
412
+ const createRegistry = (components) => {
413
+ const registry$1 = {
414
+ components: {
415
+ schemas: {
416
+ dynamicSchemaCount: 0,
417
+ input: /* @__PURE__ */ new Map(),
418
+ output: /* @__PURE__ */ new Map(),
419
+ ids: /* @__PURE__ */ new Map(),
420
+ manual: /* @__PURE__ */ new Map()
421
+ },
422
+ headers: {
423
+ ids: /* @__PURE__ */ new Map(),
424
+ seen: /* @__PURE__ */ new WeakMap()
425
+ },
426
+ requestBodies: {
427
+ ids: /* @__PURE__ */ new Map(),
428
+ seen: /* @__PURE__ */ new WeakMap()
429
+ },
430
+ responses: {
431
+ ids: /* @__PURE__ */ new Map(),
432
+ seen: /* @__PURE__ */ new WeakMap()
433
+ },
434
+ parameters: {
435
+ ids: /* @__PURE__ */ new Map(),
436
+ seen: /* @__PURE__ */ new WeakMap()
437
+ },
438
+ callbacks: {
439
+ ids: /* @__PURE__ */ new Map(),
440
+ seen: /* @__PURE__ */ new WeakMap()
441
+ },
442
+ pathItems: {
443
+ ids: /* @__PURE__ */ new Map(),
444
+ seen: /* @__PURE__ */ new WeakMap()
445
+ }
446
+ },
447
+ addSchema: (schema, path, opts) => {
448
+ const io = opts?.io ?? "output";
449
+ const schemaObject = {};
450
+ registry$1.components.schemas[io].set(path.join(" > "), {
451
+ schemaObject,
452
+ zodType: schema
453
+ });
454
+ return schemaObject;
455
+ },
456
+ addParameter: (parameter, path, opts) => {
457
+ const seenParameter = registry$1.components.parameters.seen.get(parameter);
458
+ if (seenParameter) return seenParameter;
459
+ const meta = globalRegistry.get(parameter);
460
+ const name = opts?.location?.name ?? meta?.param?.name;
461
+ const inLocation = opts?.location?.in ?? meta?.param?.in;
462
+ if (!name || !inLocation) throw new Error(`Parameter at ${path.join(" > ")} is missing \`.meta({ param: { name, in } })\` information`);
463
+ const schemaObject = registry$1.addSchema(parameter, [...path, "schema"], { io: "input" });
464
+ const { id: metaId,...rest } = meta?.param ?? {};
465
+ const parameterObject = {
466
+ ...rest,
467
+ name,
468
+ in: inLocation,
469
+ schema: schemaObject
470
+ };
471
+ if (isRequired(parameter, "input")) parameterObject.required = true;
472
+ if (!parameterObject.description && meta?.description) parameterObject.description = meta.description;
473
+ const id = metaId ?? opts?.manualId;
474
+ if (id) {
475
+ if (registry$1.components.parameters.ids.has(id)) throw new Error(`Schema "${id}" is already registered`);
476
+ const ref = { $ref: `#/components/parameters/${id}` };
477
+ registry$1.components.parameters.seen.set(parameter, ref);
478
+ registry$1.components.parameters.ids.set(id, parameterObject);
479
+ return ref;
480
+ }
481
+ registry$1.components.parameters.seen.set(parameter, parameterObject);
482
+ return parameterObject;
483
+ },
484
+ addHeader: (header, path, opts) => {
485
+ const seenHeader = registry$1.components.headers.seen.get(header);
486
+ if (seenHeader) return seenHeader;
487
+ const meta = globalRegistry.get(header);
488
+ const { id: metaId,...rest } = meta?.header ?? {};
489
+ const id = metaId ?? opts?.manualId;
490
+ const headerObject = rest;
491
+ if (isRequired(header, "output")) headerObject.required = true;
492
+ if (!headerObject.description && meta?.description) headerObject.description = meta.description;
493
+ headerObject.schema = registry$1.addSchema(header, [...path, "schema"], { io: "output" });
494
+ if (id) {
495
+ if (registry$1.components.schemas.ids.has(id)) throw new Error(`Schema "${id}" is already registered`);
496
+ const ref = { $ref: `#/components/headers/${id}` };
497
+ registry$1.components.headers.ids.set(id, headerObject);
498
+ registry$1.components.headers.seen.set(header, ref);
499
+ return ref;
500
+ }
501
+ registry$1.components.headers.seen.set(header, headerObject);
502
+ return headerObject;
503
+ },
504
+ addRequestBody: (requestBody, path, opts) => {
505
+ const seenRequestBody = registry$1.components.requestBodies.seen.get(requestBody);
506
+ if (seenRequestBody) return seenRequestBody;
507
+ const { content, id: metaId,...rest } = requestBody;
508
+ const requestBodyObject = {
509
+ ...rest,
510
+ content: createContent(content, {
511
+ registry: registry$1,
512
+ io: "input"
513
+ }, [...path, "content"])
514
+ };
515
+ const id = metaId ?? opts?.manualId;
516
+ if (id) {
517
+ if (registry$1.components.requestBodies.ids.has(id)) throw new Error(`RequestBody "${id}" is already registered`);
518
+ const ref = { $ref: `#/components/requestBodies/${id}` };
519
+ registry$1.components.requestBodies.ids.set(id, requestBodyObject);
520
+ registry$1.components.requestBodies.seen.set(requestBody, ref);
521
+ return ref;
522
+ }
523
+ registry$1.components.requestBodies.seen.set(requestBody, requestBodyObject);
524
+ return requestBodyObject;
525
+ },
526
+ addPathItem: (pathItem, path, opts) => {
527
+ const seenPathItem = registry$1.components.pathItems.seen.get(pathItem);
528
+ if (seenPathItem) return seenPathItem;
529
+ const pathItemObject = {};
530
+ const { id: metaId,...rest } = pathItem;
531
+ const id = metaId ?? opts?.manualId;
532
+ for (const [key, value] of Object.entries(rest)) {
533
+ if (isISpecificationExtension(key)) {
534
+ pathItemObject[key] = value;
535
+ continue;
536
+ }
537
+ if (key === "get" || key === "put" || key === "post" || key === "delete" || key === "options" || key === "head" || key === "patch" || key === "trace") {
538
+ pathItemObject[key] = createOperation(value, registry$1, [...path, key]);
539
+ continue;
540
+ }
541
+ if (key === "parameters") {
542
+ pathItemObject[key] = createManualParameters(value, registry$1, [...path, key]);
543
+ continue;
544
+ }
545
+ pathItemObject[key] = value;
546
+ }
547
+ if (id) {
548
+ if (registry$1.components.pathItems.ids.has(id)) throw new Error(`PathItem "${id}" is already registered`);
549
+ const ref = { $ref: `#/components/pathItems/${id}` };
550
+ registry$1.components.pathItems.ids.set(id, pathItemObject);
551
+ registry$1.components.pathItems.seen.set(pathItem, ref);
552
+ return ref;
553
+ }
554
+ registry$1.components.pathItems.seen.set(pathItem, pathItemObject);
555
+ return pathItemObject;
556
+ },
557
+ addResponse: (response, path, opts) => {
558
+ const seenResponse = registry$1.components.responses.seen.get(response);
559
+ if (seenResponse) return seenResponse;
560
+ const { content, headers, id: metaId,...rest } = response;
561
+ const responseObject = rest;
562
+ const maybeHeaders = createHeaders(headers, registry$1, [...path, "headers"]);
563
+ if (maybeHeaders) responseObject.headers = maybeHeaders;
564
+ if (content) responseObject.content = createContent(content, {
565
+ registry: registry$1,
566
+ io: "output"
567
+ }, [...path, "content"]);
568
+ const id = metaId ?? opts?.manualId;
569
+ if (id) {
570
+ if (registry$1.components.responses.ids.has(id)) throw new Error(`Response "${id}" is already registered`);
571
+ const ref = { $ref: `#/components/responses/${id}` };
572
+ registry$1.components.responses.ids.set(id, responseObject);
573
+ registry$1.components.responses.seen.set(response, ref);
574
+ return ref;
575
+ }
576
+ registry$1.components.responses.seen.set(response, responseObject);
577
+ return responseObject;
578
+ },
579
+ addCallback: (callback, path, opts) => {
580
+ const seenCallback = registry$1.components.callbacks.seen.get(callback);
581
+ if (seenCallback) return seenCallback;
582
+ const { id: metaId,...rest } = callback;
583
+ const callbackObject = {};
584
+ for (const [name, pathItem] of Object.entries(rest)) {
585
+ if (isISpecificationExtension(name)) {
586
+ callbackObject[name] = pathItem;
587
+ continue;
588
+ }
589
+ callbackObject[name] = registry$1.addPathItem(pathItem, [...path, name]);
590
+ }
591
+ const id = metaId ?? opts?.manualId;
592
+ if (id) {
593
+ if (registry$1.components.callbacks.ids.has(id)) throw new Error(`Callback "${id}" is already registered`);
594
+ const ref = { $ref: `#/components/callbacks/${id}` };
595
+ registry$1.components.callbacks.ids.set(id, callbackObject);
596
+ registry$1.components.callbacks.seen.set(callback, ref);
597
+ return ref;
598
+ }
599
+ registry$1.components.callbacks.seen.set(callback, callbackObject);
600
+ return callbackObject;
601
+ }
602
+ };
603
+ registerSchemas(components?.schemas, registry$1);
604
+ registerParameters(components?.parameters, registry$1);
605
+ registerHeaders(components?.headers, registry$1);
606
+ registerResponses(components?.responses, registry$1);
607
+ registerPathItems(components?.pathItems, registry$1);
608
+ registerRequestBodies(components?.requestBodies, registry$1);
609
+ registerCallbacks(components?.callbacks, registry$1);
610
+ return registry$1;
611
+ };
612
+ const registerSchemas = (schemas, registry$1) => {
613
+ if (!schemas) return;
614
+ for (const [key, schema] of Object.entries(schemas)) {
615
+ if (isAnyZodType(schema)) {
616
+ const id = globalRegistry.get(schema)?.id ?? key;
617
+ registry$1.components.schemas.manual.set(id, {
618
+ input: { schemaObject: {} },
619
+ output: { schemaObject: {} },
620
+ zodType: schema
621
+ });
622
+ continue;
623
+ }
624
+ registry$1.components.schemas.ids.set(key, schema);
625
+ }
626
+ };
627
+ const registerParameters = (parameters, registry$1) => {
628
+ if (!parameters) return;
629
+ for (const [key, schema] of Object.entries(parameters)) {
630
+ if (isAnyZodType(schema)) {
631
+ const path = [
632
+ "components",
633
+ "parameters",
634
+ key
635
+ ];
636
+ registry$1.addParameter(schema, path, { manualId: key });
637
+ continue;
638
+ }
639
+ registry$1.components.parameters.ids.set(key, schema);
640
+ }
641
+ };
642
+ const registerHeaders = (headers, registry$1) => {
643
+ if (!headers) return;
644
+ for (const [key, schema] of Object.entries(headers)) {
645
+ if (isAnyZodType(schema)) {
646
+ const path = [
647
+ "components",
648
+ "headers",
649
+ key
650
+ ];
651
+ registry$1.addHeader(schema, path, { manualId: key });
652
+ continue;
653
+ }
654
+ registry$1.components.headers.ids.set(key, schema);
655
+ }
656
+ };
657
+ const registerResponses = (responses, registry$1) => {
658
+ if (!responses) return;
659
+ for (const [key, schema] of Object.entries(responses)) {
660
+ const responseObject = registry$1.addResponse(schema, [
661
+ "components",
662
+ "responses",
663
+ key
664
+ ], { manualId: key });
665
+ registry$1.components.responses.ids.set(key, responseObject);
666
+ registry$1.components.responses.seen.set(schema, responseObject);
667
+ }
668
+ };
669
+ const registerRequestBodies = (requestBodies, registry$1) => {
670
+ if (!requestBodies) return;
671
+ for (const [key, schema] of Object.entries(requestBodies)) {
672
+ if (isAnyZodType(schema)) {
673
+ registry$1.addRequestBody(schema, [
674
+ "components",
675
+ "requestBodies",
676
+ key
677
+ ], { manualId: key });
678
+ continue;
679
+ }
680
+ registry$1.components.requestBodies.ids.set(key, schema);
681
+ }
682
+ };
683
+ const registerCallbacks = (callbacks, registry$1) => {
684
+ if (!callbacks) return;
685
+ for (const [key, schema] of Object.entries(callbacks)) registry$1.addCallback(schema, [
686
+ "components",
687
+ "callbacks",
688
+ key
689
+ ], { manualId: key });
690
+ };
691
+ const registerPathItems = (pathItems, registry$1) => {
692
+ if (!pathItems) return;
693
+ for (const [key, schema] of Object.entries(pathItems)) registry$1.addPathItem(schema, [
694
+ "components",
695
+ "pathItems",
696
+ key
697
+ ], { manualId: key });
698
+ };
699
+ const createIOSchemas = (ctx) => {
700
+ const { schemas, components, manual } = createSchemas(Object.fromEntries(ctx.registry.components.schemas[ctx.io]), ctx);
701
+ for (const [key, schema] of Object.entries(components)) {
702
+ if (ctx.registry.components.schemas.ids.has(key)) throw new Error(`Schema "${key}" is already registered`);
703
+ ctx.registry.components.schemas.ids.set(key, schema);
704
+ }
705
+ for (const [key, schema] of Object.entries(schemas)) {
706
+ const ioSchema = ctx.registry.components.schemas[ctx.io].get(key);
707
+ if (ioSchema) Object.assign(ioSchema.schemaObject, schema);
708
+ }
709
+ for (const [key, value] of Object.entries(manual)) {
710
+ const manualSchema = ctx.registry.components.schemas.manual.get(key);
711
+ if (!manualSchema) continue;
712
+ if (components[key]) manualSchema[ctx.io].used = true;
713
+ Object.assign(manualSchema[ctx.io].schemaObject, value);
714
+ }
715
+ };
716
+ const createManualSchemas = (registry$1) => {
717
+ for (const [key, value] of registry$1.components.schemas.manual) if (!value.input.used) {
718
+ const io = globalRegistry.get(value.zodType)?.unusedIO ?? "output";
719
+ const schema = value[io].schemaObject;
720
+ registry$1.components.schemas.ids.set(key, schema);
721
+ }
722
+ };
723
+ const createComponents = (registry$1, opts) => {
724
+ createIOSchemas({
725
+ registry: registry$1,
726
+ io: "input",
727
+ opts
728
+ });
729
+ createIOSchemas({
730
+ registry: registry$1,
731
+ io: "output",
732
+ opts
733
+ });
734
+ createManualSchemas(registry$1);
735
+ const components = {};
736
+ if (registry$1.components.schemas.ids.size > 0) components.schemas = Object.fromEntries(registry$1.components.schemas.ids);
737
+ if (registry$1.components.headers.ids.size > 0) components.headers = Object.fromEntries(registry$1.components.headers.ids);
738
+ if (registry$1.components.requestBodies.ids.size > 0) components.requestBodies = Object.fromEntries(registry$1.components.requestBodies.ids);
739
+ if (registry$1.components.responses.ids.size > 0) components.responses = Object.fromEntries(registry$1.components.responses.ids);
740
+ if (registry$1.components.parameters.ids.size > 0) components.parameters = Object.fromEntries(registry$1.components.parameters.ids);
741
+ if (registry$1.components.callbacks.ids.size > 0) components.callbacks = Object.fromEntries(registry$1.components.callbacks.ids);
742
+ if (registry$1.components.pathItems.ids.size > 0) components.pathItems = Object.fromEntries(registry$1.components.pathItems.ids);
743
+ return components;
744
+ };
745
+
746
+ //#endregion
747
+ export { createComponents, createPaths, createRegistry, createSchema, isAnyZodType, unwrapZodObject };