From a84d1e7fb4c783b48b88e8dcc6dd932dc15c5fa4 Mon Sep 17 00:00:00 2001 From: theoriginalbit <1377564+theoriginalbit@users.noreply.github.com> Date: Sat, 7 Sep 2024 11:24:31 +1000 Subject: [PATCH 01/13] Generate enums for server variables --- .../Translator/CommonTypes/Constants.swift | 9 ++ .../TypesTranslator/translateServers.swift | 37 +++-- .../translateServersVariables.swift | 132 ++++++++++++++++++ .../ReferenceSources/Petstore/Types.swift | 67 +++++++-- 4 files changed, 220 insertions(+), 25 deletions(-) create mode 100644 Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift index 52270eb6..8231fb69 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift @@ -56,6 +56,15 @@ enum Constants { /// The prefix of each generated method name. static let propertyPrefix: String = "server" + + /// The name of the server variables namespace. + static let variablesNamespace: String = "Variables" + + /// The prefix of the namespace that contains server specific variables. + static let serverVariablesNamespacePrefix: String = "Server" + + /// The name of the generated default computed property. + static let defaultPropertyName: String = "default" } /// Constants related to the configuration type, which is used by both diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift index bb7a6552..4bfbf718 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift @@ -29,24 +29,30 @@ extension TypesFileTranslator { (originalKey: key, swiftSafeKey: swiftSafeName(for: key), value: value) } let parameters: [ParameterDescription] = safeVariables.map { (originalKey, swiftSafeKey, value) in - .init(label: swiftSafeKey, type: .init(TypeName.string), defaultValue: .literal(value.default)) + let memberPath: [String] = [ + Constants.ServerURL.variablesNamespace, + translateServerVariablesEnumName(for: index), + translateVariableToEnumName((originalKey, value)) + ] + return .init( + label: swiftSafeName(for: originalKey), + type: .member(memberPath), + defaultValue: .identifierType(.member(memberPath + CollectionOfOne(Constants.ServerURL.defaultPropertyName))) + ) } let variableInitializers: [Expression] = safeVariables.map { (originalKey, swiftSafeKey, value) in - let allowedValuesArg: FunctionArgumentDescription? - if let allowedValues = value.enum { - allowedValuesArg = .init( - label: "allowedValues", - expression: .literal(.array(allowedValues.map { .literal($0) })) - ) - } else { - allowedValuesArg = nil - } return .dot("init") .call( [ .init(label: "name", expression: .literal(originalKey)), - .init(label: "value", expression: .identifierPattern(swiftSafeKey)), - ] + (allowedValuesArg.flatMap { [$0] } ?? []) + .init( + label: "value", + expression: .memberAccess(.init( + left: .identifierPattern(swiftSafeKey), + right: "rawValue" + )) + ), + ] ) } let methodDecl = Declaration.commentable( @@ -81,7 +87,12 @@ extension TypesFileTranslator { /// - Parameter servers: The servers to include in the extension. /// - Returns: A declaration of an enum namespace of the server URLs type. func translateServers(_ servers: [OpenAPI.Server]) -> Declaration { - let serverDecls = servers.enumerated().map(translateServer) + var serverDecls = servers.enumerated().map(translateServer) + + if let variablesDecl = translateServersVariables(servers) { + serverDecls.insert(variablesDecl, at: 0) + } + return .commentable( .doc("Server URLs defined in the OpenAPI document."), .enum(accessModifier: config.access, name: Constants.ServerURL.namespace, members: serverDecls) diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift new file mode 100644 index 00000000..e5bc35fc --- /dev/null +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift @@ -0,0 +1,132 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import OpenAPIKit + +extension TypesFileTranslator { + + /// Returns the name used for the enum which represents a server variable defined in the OpenAPI + /// document. + /// - Parameter variable: The variable information. + /// - Returns: A name that can be safely used for the enum. + func translateVariableToEnumName(_ variable: (key: String, value: OpenAPI.Server.Variable)) -> String { + return swiftSafeName(for: variable.key.localizedCapitalized) + } + + /// Returns the name used for the namespace (enum) which contains a specific server's variables. + /// - Parameter index: The array index of the server. + /// - Returns: A name that can be safely used for the namespace. + func translateServerVariablesEnumName(for index: Int) -> String { + return "\(Constants.ServerURL.serverVariablesNamespacePrefix)\(index + 1)" + } + + /// Returns a declaration of a variable enum case for the provided value. If the value can be + /// safely represented as an identifier then the enum case is name only, otherwise the case + /// will have a raw value set to the provided value to satisfy the OpenAPI document + /// requirements. + /// - Parameter value: The variable's enum value. + /// - Returns: A enum case declaration named by the supplied value. + func translateVariableCase(_ value: String) -> Declaration { + let caseName = swiftSafeName(for: value) + if caseName == value { + return .enumCase(name: caseName, kind: .nameOnly) + } else { + return .enumCase(name: caseName, kind: .nameWithRawValue(.string(value))) + } + } + + /// Returns a declaration of a variable enum defined in the OpenAPI document. Including + /// a static computed property named default which returns the default defined in the + /// document. + /// - Parameter variable: The variable information. + /// - Returns: An enum declaration. + func translateServerVariable(_ variable: (key: String, value: OpenAPI.Server.Variable)) -> Declaration { + let enumName = translateVariableToEnumName(variable) + var casesDecls: [Declaration] + + if let enums = variable.value.enum { + casesDecls = enums.map(translateVariableCase) + } else { + casesDecls = [translateVariableCase(variable.value.default)] + } + casesDecls.append(.commentable( + .doc("The default variable."), + .variable( + accessModifier: config.access, + isStatic: true, + kind: .var, + left: .identifierPattern("`\(Constants.ServerURL.defaultPropertyName)`"), + type: .member(enumName), + getter: [ + .expression( + .return( + .memberAccess(.init( + left: .identifierPattern(enumName), + right: swiftSafeName(for: variable.value.default) + )) + ) + ), + ] + ) + )) + + return .commentable( + .doc(""" + The "\(variable.key)" variable defined in the OpenAPI document. + + The default value is "\(variable.value.default)". + """), + .enum(isFrozen: true, accessModifier: config.access, name: enumName, conformances: [TypeName.string.fullyQualifiedSwiftName], members: casesDecls) + ) + } + + /// Returns a declaration of a namespace (enum) for a specific server and will define + /// one enum member for each of the server's variables in the OpenAPI Document. + /// If the server does not define variables, no declaration will be generated. + /// - Parameters: + /// - index: The index of the server in the list of servers defined + /// in the OpenAPI document. + /// - server: The server variables information. + /// - Returns: A declaration of the server variables namespace, or `nil` if no + /// variables are declared. + func translateServerVariables(index: Int, server: OpenAPI.Server) -> Declaration? { + if server.variables.isEmpty { + return nil + } + + let typeName = translateServerVariablesEnumName(for: index) + let variableDecls = server.variables.map(translateServerVariable) + return .commentable( + .doc("The variables for Server\(index + 1) defined in the OpenAPI document."), + .enum(accessModifier: config.access, name: typeName, members: variableDecls) + ) + } + + /// Returns a declaration of a namespace (enum) called "Variables" that + /// defines one namespace (enum) per server URL that defines variables + /// in the OpenAPI document. If no server URL defines variables then no + /// declaration is generated. + /// - Parameter servers: The servers to include in the extension. + /// - Returns: A declaration of an enum namespace of the server URLs type. + func translateServersVariables(_ servers: [OpenAPI.Server]) -> Declaration? { + let variableDecls = servers.enumerated().compactMap(translateServerVariables) + if variableDecls.isEmpty { + return nil + } + + return .commentable( + .doc("Server URL variables defined in the OpenAPI document."), + .enum(accessModifier: config.access, name: Constants.ServerURL.variablesNamespace, members: variableDecls) + ) + } +} diff --git a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift index 818aff50..f08b7b90 100644 --- a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift +++ b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift @@ -153,6 +153,53 @@ extension APIProtocol { /// Server URLs defined in the OpenAPI document. public enum Servers { + /// Server URL variables defined in the OpenAPI document. + public enum Variables { + /// The variables for Server3 defined in the OpenAPI document. + public enum Server3 { + /// The "protocol" variable defined in the OpenAPI document. + /// + /// The default value is "https". + @frozen public enum _Protocol: Swift.String { + case https + /// The default variable. + public static var `default`: _Protocol { + return _Protocol.https + } + } + /// The "subdomain" variable defined in the OpenAPI document. + /// + /// The default value is "test". + @frozen public enum Subdomain: Swift.String { + case test + /// The default variable. + public static var `default`: Subdomain { + return Subdomain.test + } + } + /// The "port" variable defined in the OpenAPI document. + /// + /// The default value is "443". + @frozen public enum Port: Swift.String { + case _443 = "443" + case _8443 = "8443" + /// The default variable. + public static var `default`: Port { + return Port._443 + } + } + /// The "basePath" variable defined in the OpenAPI document. + /// + /// The default value is "v1". + @frozen public enum Basepath: Swift.String { + case v1 + /// The default variable. + public static var `default`: Basepath { + return Basepath.v1 + } + } + } + } /// Example Petstore implementation service public static func server1() throws -> Foundation.URL { try Foundation.URL( @@ -174,33 +221,29 @@ public enum Servers { /// - port: /// - basePath: The base API path. public static func server3( - _protocol: Swift.String = "https", - subdomain: Swift.String = "test", - port: Swift.String = "443", - basePath: Swift.String = "v1" + _protocol: Variables.Server3._Protocol = Variables.Server3._Protocol.default, + subdomain: Variables.Server3.Subdomain = Variables.Server3.Subdomain.default, + port: Variables.Server3.Port = Variables.Server3.Port.default, + basePath: Variables.Server3.Basepath = Variables.Server3.Basepath.default ) throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "{protocol}://{subdomain}.example.com:{port}/{basePath}", variables: [ .init( name: "protocol", - value: _protocol + value: _protocol.rawValue ), .init( name: "subdomain", - value: subdomain + value: subdomain.rawValue ), .init( name: "port", - value: port, - allowedValues: [ - "443", - "8443" - ] + value: port.rawValue ), .init( name: "basePath", - value: basePath + value: basePath.rawValue ) ] ) From 1e73c298e9cb8a007703734dbf1b5f25da4beaed Mon Sep 17 00:00:00 2001 From: theoriginalbit <1377564+theoriginalbit@users.noreply.github.com> Date: Thu, 12 Sep 2024 21:10:35 +1000 Subject: [PATCH 02/13] Generated enums for server variables are now feature flagged --- .../_OpenAPIGeneratorCore/FeatureFlags.swift | 4 + .../TypesTranslator/translateServers.swift | 72 +- .../translateServersVariables.swift | 312 +- .../FileBasedReferenceTests.swift | 28 +- .../ReferenceSources/Petstore/Types.swift | 67 +- .../Client.swift | 927 +++++ .../Server.swift | 1015 ++++++ .../Petstore_ServerVariablesEnums/Types.swift | 3071 +++++++++++++++++ 8 files changed, 5331 insertions(+), 165 deletions(-) create mode 100644 Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Client.swift create mode 100644 Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Server.swift create mode 100644 Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Types.swift diff --git a/Sources/_OpenAPIGeneratorCore/FeatureFlags.swift b/Sources/_OpenAPIGeneratorCore/FeatureFlags.swift index ca3d5682..4d8bb33f 100644 --- a/Sources/_OpenAPIGeneratorCore/FeatureFlags.swift +++ b/Sources/_OpenAPIGeneratorCore/FeatureFlags.swift @@ -28,6 +28,10 @@ public enum FeatureFlag: String, Hashable, Codable, CaseIterable, Sendable { // needs to be here for the enum to compile case empty + + /// When enabled any server URL templating variables that have a defined + /// enum field will be generated as an enum instead of raw Strings. + case serverVariablesAsEnums = "ServerVariablesEnums" } /// A set of enabled feature flags. diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift index 4bfbf718..aff1be9d 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift @@ -14,49 +14,33 @@ import OpenAPIKit extension TypesFileTranslator { - /// Returns a declaration of a server URL static method defined in - /// the OpenAPI document. + /// the OpenAPI document. Also appends server variables enums + /// into the variables namespace parameter, if any enums were + /// generated. /// - Parameters: /// - index: The index of the server in the list of servers defined /// in the OpenAPI document. /// - server: The server URL information. + /// - variablesNamespace: The enum namespace which is to contain + /// any variable enum definitions that may be required. /// - Returns: A static method declaration, and a name for the variable to /// declare the method under. - func translateServer(index: Int, server: OpenAPI.Server) -> Declaration { - let methodName = "\(Constants.ServerURL.propertyPrefix)\(index+1)" - let safeVariables = server.variables.map { (key, value) in - (originalKey: key, swiftSafeKey: swiftSafeName(for: key), value: value) - } - let parameters: [ParameterDescription] = safeVariables.map { (originalKey, swiftSafeKey, value) in - let memberPath: [String] = [ - Constants.ServerURL.variablesNamespace, - translateServerVariablesEnumName(for: index), - translateVariableToEnumName((originalKey, value)) - ] - return .init( - label: swiftSafeName(for: originalKey), - type: .member(memberPath), - defaultValue: .identifierType(.member(memberPath + CollectionOfOne(Constants.ServerURL.defaultPropertyName))) - ) - } - let variableInitializers: [Expression] = safeVariables.map { (originalKey, swiftSafeKey, value) in - return .dot("init") - .call( - [ - .init(label: "name", expression: .literal(originalKey)), - .init( - label: "value", - expression: .memberAccess(.init( - left: .identifierPattern(swiftSafeKey), - right: "rawValue" - )) - ), - ] - ) + func translateServer(index: Int, server: OpenAPI.Server, variablesNamespace: inout EnumDescription) -> Declaration { + let serverVariables = translateServerVariableNamespace(index: index, server: server, variablesNamespaceName: variablesNamespace.name) + + if let serverVariablesNamespace = serverVariables.decl { + variablesNamespace.members.append(serverVariablesNamespace) } + + let parameters = serverVariables.variables.map(\.parameter) + let variableInitializers = serverVariables.variables.map(\.initializer) + let functionComments = serverVariables.variables.map(\.functionComment) + + let methodName = "\(Constants.ServerURL.propertyPrefix)\(index + 1)" + let methodDecl = Declaration.commentable( - .functionComment(abstract: server.description, parameters: safeVariables.map { ($1, $2.description) }), + .functionComment(abstract: server.description, parameters: functionComments), .function( accessModifier: config.access, kind: .function(name: methodName, isStatic: true), @@ -87,10 +71,24 @@ extension TypesFileTranslator { /// - Parameter servers: The servers to include in the extension. /// - Returns: A declaration of an enum namespace of the server URLs type. func translateServers(_ servers: [OpenAPI.Server]) -> Declaration { - var serverDecls = servers.enumerated().map(translateServer) + var variablesNamespace = EnumDescription( + accessModifier: config.access, + name: Constants.ServerURL.variablesNamespace + ) + + var serverDecls: [Declaration] = [] + + + for (index, decl) in servers.enumerated() { + let serverDecl = translateServer(index: index, server: decl, variablesNamespace: &variablesNamespace) + serverDecls.append(serverDecl) + } - if let variablesDecl = translateServersVariables(servers) { - serverDecls.insert(variablesDecl, at: 0) + if !variablesNamespace.members.isEmpty { + serverDecls.insert(.commentable( + .doc("Server URL variables defined in the OpenAPI document."), + .enum(variablesNamespace) + ), at: 0) } return .commentable( diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift index e5bc35fc..437be5f3 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift @@ -14,20 +14,24 @@ import OpenAPIKit extension TypesFileTranslator { + /// Represents a server variable and the function of generation that should be applied. + protocol TranslatedServerVariable { + /// Returns the declaration (enum) that should be added to the `Variables.Server#` + /// namespace. If the server variable does not require any codegen then it should + /// return `nil`. + var declaration: Declaration? { get } - /// Returns the name used for the enum which represents a server variable defined in the OpenAPI - /// document. - /// - Parameter variable: The variable information. - /// - Returns: A name that can be safely used for the enum. - func translateVariableToEnumName(_ variable: (key: String, value: OpenAPI.Server.Variable)) -> String { - return swiftSafeName(for: variable.key.localizedCapitalized) - } + /// Returns the description of the parameter that will be used to define the variable + /// in the static method for a given server. + var parameter: ParameterDescription { get } + + /// Returns an expression for the variable initializer that is used in the body of a server's + /// static method by passing it along to the URL resolver. + var initializer: Expression { get } - /// Returns the name used for the namespace (enum) which contains a specific server's variables. - /// - Parameter index: The array index of the server. - /// - Returns: A name that can be safely used for the namespace. - func translateServerVariablesEnumName(for index: Int) -> String { - return "\(Constants.ServerURL.serverVariablesNamespacePrefix)\(index + 1)" + /// Returns the description of this variables documentation for the function comment of + /// the server's static method. + var functionComment: (name: String, comment: String?) { get } } /// Returns a declaration of a variable enum case for the provided value. If the value can be @@ -50,43 +54,22 @@ extension TypesFileTranslator { /// document. /// - Parameter variable: The variable information. /// - Returns: An enum declaration. - func translateServerVariable(_ variable: (key: String, value: OpenAPI.Server.Variable)) -> Declaration { - let enumName = translateVariableToEnumName(variable) - var casesDecls: [Declaration] - - if let enums = variable.value.enum { - casesDecls = enums.map(translateVariableCase) - } else { - casesDecls = [translateVariableCase(variable.value.default)] - } - casesDecls.append(.commentable( - .doc("The default variable."), - .variable( - accessModifier: config.access, - isStatic: true, - kind: .var, - left: .identifierPattern("`\(Constants.ServerURL.defaultPropertyName)`"), - type: .member(enumName), - getter: [ - .expression( - .return( - .memberAccess(.init( - left: .identifierPattern(enumName), - right: swiftSafeName(for: variable.value.default) - )) - ) - ), - ] + func translateServerVariable(key: String, variable: OpenAPI.Server.Variable, variablesNamespaceName: String, serverVariableNamespaceName: String) -> any TranslatedServerVariable { + guard variable.enum != nil, config.featureFlags.contains(.serverVariablesAsEnums) else { + return RawStringTranslatedServerVariable( + key: key, + variable: variable, + asSwiftSafeName: swiftSafeName(for:) ) - )) - - return .commentable( - .doc(""" - The "\(variable.key)" variable defined in the OpenAPI document. + } - The default value is "\(variable.value.default)". - """), - .enum(isFrozen: true, accessModifier: config.access, name: enumName, conformances: [TypeName.string.fullyQualifiedSwiftName], members: casesDecls) + return GeneratedEnumTranslatedServerVariable( + key: key, + variable: variable, + variablesNamespaceName: variablesNamespaceName, + serverVariablesNamespaceName: serverVariableNamespaceName, + accessModifier: config.access, + asSwiftSafeName: swiftSafeName(for:) ) } @@ -99,34 +82,225 @@ extension TypesFileTranslator { /// - server: The server variables information. /// - Returns: A declaration of the server variables namespace, or `nil` if no /// variables are declared. - func translateServerVariables(index: Int, server: OpenAPI.Server) -> Declaration? { - if server.variables.isEmpty { - return nil + func translateServerVariableNamespace(index: Int, server: OpenAPI.Server, variablesNamespaceName: String) -> TranslatedServerVariableNamespace { + let serverVariableNamespaceName = "\(Constants.ServerURL.serverVariablesNamespacePrefix)\(index + 1)" + let variables = server.variables.map { variableEntry in + translateServerVariable( + key: variableEntry.0, + variable: variableEntry.1, + variablesNamespaceName: variablesNamespaceName, + serverVariableNamespaceName: serverVariableNamespaceName + ) } - let typeName = translateServerVariablesEnumName(for: index) - let variableDecls = server.variables.map(translateServerVariable) - return .commentable( - .doc("The variables for Server\(index + 1) defined in the OpenAPI document."), - .enum(accessModifier: config.access, name: typeName, members: variableDecls) + return TranslatedServerVariableNamespace( + index: index, + name: serverVariableNamespaceName, + accessModifier: config.access, + variables: variables ) } - /// Returns a declaration of a namespace (enum) called "Variables" that - /// defines one namespace (enum) per server URL that defines variables - /// in the OpenAPI document. If no server URL defines variables then no - /// declaration is generated. - /// - Parameter servers: The servers to include in the extension. - /// - Returns: A declaration of an enum namespace of the server URLs type. - func translateServersVariables(_ servers: [OpenAPI.Server]) -> Declaration? { - let variableDecls = servers.enumerated().compactMap(translateServerVariables) - if variableDecls.isEmpty { - return nil + // MARK: Generators + + /// Represents a namespace (enum) that contains all the defined variables for a given server. + /// If none of the variables have a + struct TranslatedServerVariableNamespace { + let index: Int + let name: String + let accessModifier: AccessModifier + let variables: [any TranslatedServerVariable] + + var decl: Declaration? { + let variableDecls = variables.compactMap(\.declaration) + if variableDecls.isEmpty { + return nil + } + return .commentable( + .doc("The variables for Server\(index + 1) defined in the OpenAPI document."), + .enum( + accessModifier: accessModifier, + name: name, + members: variableDecls + ) + ) } + } - return .commentable( - .doc("Server URL variables defined in the OpenAPI document."), - .enum(accessModifier: config.access, name: Constants.ServerURL.variablesNamespace, members: variableDecls) - ) + /// Represents a variable that is required to be represented as a `Swift.String`. + private struct RawStringTranslatedServerVariable: TranslatedServerVariable { + let key: String + let swiftSafeKey: String + let variable: OpenAPI.Server.Variable + + init(key: String, variable: OpenAPI.Server.Variable, asSwiftSafeName: @escaping (String) -> String) { + self.key = key + swiftSafeKey = asSwiftSafeName(key) + self.variable = variable + } + + /// A variable being represented by a `Swift.String` does not have a declaration that needs to + /// be added to the `Variables.Server#` namespace. + var declaration: Declaration? { nil } + + /// Returns the description of the parameter that will be used to define the variable + /// in the static method for a given server. + var parameter: ParameterDescription { + return .init( + label: swiftSafeKey, + type: .init(TypeName.string), + defaultValue: .literal(variable.default) + ) + } + + /// Returns an expression for the variable initializer that is used in the body of a server's + /// static method by passing it along to the URL resolver. + var initializer: Expression { + var arguments: [FunctionArgumentDescription] = [ + .init(label: "name", expression: .literal(key)), + .init(label: "value", expression: .identifierPattern(swiftSafeKey)), + ] + if let allowedValues = variable.enum { + arguments.append(.init( + label: "allowedValues", + expression: .literal(.array(allowedValues.map { .literal($0) })) + )) + } + return .dot("init").call(arguments) + } + + /// Returns the description of this variables documentation for the function comment of + /// the server's static method. + var functionComment: (name: String, comment: String?) { + (name: swiftSafeKey, comment: variable.description) + } + } + + /// Represents a variable that will be generated as an enum and added to the `Variables.Server#` + /// namespace. The enum will contain a `default` static case which returns the default defined in + /// the OpenAPI Document. + private struct GeneratedEnumTranslatedServerVariable: TranslatedServerVariable { + let key: String + let swiftSafeKey: String + let enumName: String + let variable: OpenAPI.Server.Variable + + let variablesNamespaceName: String + let serverVariablesNamespaceName: String + let accessModifier: AccessModifier + let asSwiftSafeName: (String) -> String + + init(key: String, variable: OpenAPI.Server.Variable, variablesNamespaceName: String, serverVariablesNamespaceName: String, accessModifier: AccessModifier, asSwiftSafeName: @escaping (String) -> String) { + self.key = key + swiftSafeKey = asSwiftSafeName(key) + enumName = asSwiftSafeName(key.localizedCapitalized) + self.variable = variable + + self.variablesNamespaceName = variablesNamespaceName + self.serverVariablesNamespaceName = serverVariablesNamespaceName + self.asSwiftSafeName = asSwiftSafeName + self.accessModifier = accessModifier + } + + /// Returns the declaration (enum) that should be added to the `Variables.Server#` + /// namespace. + var declaration: Declaration? { + let description: String = if let description = variable.description { + description + "\n\n" + } else { + "" + } + let casesDecls = variable.enum!.map(translateVariableCase) + CollectionOfOne( + .commentable( + .doc("The default variable."), + .variable( + accessModifier: accessModifier, + isStatic: true, + kind: .var, + left: .identifierPattern("`\(Constants.ServerURL.defaultPropertyName)`"), + type: .member(enumName), + getter: [ + .expression( + .return( + .memberAccess(.init( + left: .identifierPattern(enumName), + right: asSwiftSafeName(variable.default) + )) + ) + ), + ] + ) + ) + ) + + return .commentable( + .doc(""" + \(description)The "\(key)" variable defined in the OpenAPI document. The default value is "\(variable.default)". + """), + .enum( + isFrozen: true, + accessModifier: accessModifier, + name: enumName, + conformances: [ + TypeName.string.fullyQualifiedSwiftName, + ], + members: casesDecls + ) + ) + } + + /// Returns the description of the parameter that will be used to define the variable + /// in the static method for a given server. + var parameter: ParameterDescription { + let memberPath: [String] = [ + variablesNamespaceName, + serverVariablesNamespaceName, + enumName, + ] + + return .init( + label: swiftSafeKey, + type: .member(memberPath), + defaultValue: .identifierType(.member(memberPath + CollectionOfOne(Constants.ServerURL.defaultPropertyName))) + ) + } + + /// Returns an expression for the variable initializer that is used in the body of a server's + /// static method by passing it along to the URL resolver. + var initializer: Expression { + .dot("init").call( + [ + .init(label: "name", expression: .literal(key)), + .init(label: "value", expression: .memberAccess(.init( + left: .identifierPattern(swiftSafeKey), + right: "rawValue" + ))), + ] + ) + } + + /// Returns the description of this variables documentation for the function comment of + /// the server's static method. + var functionComment: (name: String, comment: String?) { + (name: swiftSafeKey, comment: variable.description) + } + + /// Returns an enum case declaration for a raw string enum. + /// + /// If the name does not need to be converted to a Swift safe identifier then the + /// enum case will not define a raw value and rely on the implicit generation from + /// Swift. Otherwise the enum case name will be the Swift safe name and a string + /// raw value will be set to the original name. + /// + /// - Parameter name: The original name. + /// - Returns: A declaration of an enum case. + private func translateVariableCase(_ name: String) -> Declaration { + let caseName = asSwiftSafeName(name) + if caseName == name { + return .enumCase(name: caseName, kind: .nameOnly) + } else { + return .enumCase(name: caseName, kind: .nameWithRawValue(.string(name))) + } + } } } diff --git a/Tests/OpenAPIGeneratorReferenceTests/FileBasedReferenceTests.swift b/Tests/OpenAPIGeneratorReferenceTests/FileBasedReferenceTests.swift index 75b8be78..da496100 100644 --- a/Tests/OpenAPIGeneratorReferenceTests/FileBasedReferenceTests.swift +++ b/Tests/OpenAPIGeneratorReferenceTests/FileBasedReferenceTests.swift @@ -43,6 +43,11 @@ final class FileBasedReferenceTests: XCTestCase { } func testPetstore() throws { try _test(referenceProject: .init(name: .petstore)) } + + func testPetstoreWithServerVariablesEnumsFeatureFlag() throws { + let featureFlags: FeatureFlags = [.serverVariablesAsEnums] + try _test(referenceProject: .init(name: .petstore(featureFlags)), featureFlags: featureFlags) + } // MARK: - Private @@ -97,12 +102,27 @@ final class FileBasedReferenceTests: XCTestCase { ) } - enum ReferenceProjectName: String, Hashable, CaseIterable { - case petstore + enum ReferenceProjectName: Hashable { + case petstore(FeatureFlags) + + static var petstore: Self { .petstore([]) } - var openAPIDocFileName: String { "\(rawValue).yaml" } + var openAPIDocFileName: String { + switch self { + case .petstore: + return "petstore.yaml" + } + } - var fixtureCodeDirectoryName: String { rawValue.capitalized } + var fixtureCodeDirectoryName: String { + switch self { + case let .petstore(featureFlags): + if featureFlags.isEmpty { + return "Petstore" + } + return "Petstore_" + featureFlags.map(\.rawValue).joined(separator: "_") + } + } } struct ReferenceProject: Hashable { diff --git a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift index f08b7b90..818aff50 100644 --- a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift +++ b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift @@ -153,53 +153,6 @@ extension APIProtocol { /// Server URLs defined in the OpenAPI document. public enum Servers { - /// Server URL variables defined in the OpenAPI document. - public enum Variables { - /// The variables for Server3 defined in the OpenAPI document. - public enum Server3 { - /// The "protocol" variable defined in the OpenAPI document. - /// - /// The default value is "https". - @frozen public enum _Protocol: Swift.String { - case https - /// The default variable. - public static var `default`: _Protocol { - return _Protocol.https - } - } - /// The "subdomain" variable defined in the OpenAPI document. - /// - /// The default value is "test". - @frozen public enum Subdomain: Swift.String { - case test - /// The default variable. - public static var `default`: Subdomain { - return Subdomain.test - } - } - /// The "port" variable defined in the OpenAPI document. - /// - /// The default value is "443". - @frozen public enum Port: Swift.String { - case _443 = "443" - case _8443 = "8443" - /// The default variable. - public static var `default`: Port { - return Port._443 - } - } - /// The "basePath" variable defined in the OpenAPI document. - /// - /// The default value is "v1". - @frozen public enum Basepath: Swift.String { - case v1 - /// The default variable. - public static var `default`: Basepath { - return Basepath.v1 - } - } - } - } /// Example Petstore implementation service public static func server1() throws -> Foundation.URL { try Foundation.URL( @@ -221,29 +174,33 @@ public enum Servers { /// - port: /// - basePath: The base API path. public static func server3( - _protocol: Variables.Server3._Protocol = Variables.Server3._Protocol.default, - subdomain: Variables.Server3.Subdomain = Variables.Server3.Subdomain.default, - port: Variables.Server3.Port = Variables.Server3.Port.default, - basePath: Variables.Server3.Basepath = Variables.Server3.Basepath.default + _protocol: Swift.String = "https", + subdomain: Swift.String = "test", + port: Swift.String = "443", + basePath: Swift.String = "v1" ) throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "{protocol}://{subdomain}.example.com:{port}/{basePath}", variables: [ .init( name: "protocol", - value: _protocol.rawValue + value: _protocol ), .init( name: "subdomain", - value: subdomain.rawValue + value: subdomain ), .init( name: "port", - value: port.rawValue + value: port, + allowedValues: [ + "443", + "8443" + ] ), .init( name: "basePath", - value: basePath.rawValue + value: basePath ) ] ) diff --git a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Client.swift b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Client.swift new file mode 100644 index 00000000..75c9bf22 --- /dev/null +++ b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Client.swift @@ -0,0 +1,927 @@ +// Generated by swift-openapi-generator, do not modify. +@_spi(Generated) import OpenAPIRuntime +#if os(Linux) +@preconcurrency import struct Foundation.URL +@preconcurrency import struct Foundation.Data +@preconcurrency import struct Foundation.Date +#else +import struct Foundation.URL +import struct Foundation.Data +import struct Foundation.Date +#endif +import HTTPTypes +/// Service for managing pet metadata. +/// +/// Because why not. +public struct Client: APIProtocol { + /// The underlying HTTP client. + private let client: UniversalClient + /// Creates a new client. + /// - Parameters: + /// - serverURL: The server URL that the client connects to. Any server + /// URLs defined in the OpenAPI document are available as static methods + /// on the ``Servers`` type. + /// - configuration: A set of configuration values for the client. + /// - transport: A transport that performs HTTP operations. + /// - middlewares: A list of middlewares to call before the transport. + public init( + serverURL: Foundation.URL, + configuration: Configuration = .init(), + transport: any ClientTransport, + middlewares: [any ClientMiddleware] = [] + ) { + self.client = .init( + serverURL: serverURL, + configuration: configuration, + transport: transport, + middlewares: middlewares + ) + } + private var converter: Converter { + client.converter + } + /// List all pets + /// + /// You can fetch + /// all the pets here + /// + /// - Remark: HTTP `GET /pets`. + /// - Remark: Generated from `#/paths//pets/get(listPets)`. + public func listPets(_ input: Operations.listPets.Input) async throws -> Operations.listPets.Output { + try await client.send( + input: input, + forOperation: Operations.listPets.id, + serializer: { input in + let path = try converter.renderedPath( + template: "/pets", + parameters: [] + ) + var request: HTTPTypes.HTTPRequest = .init( + soar_path: path, + method: .get + ) + suppressMutabilityWarning(&request) + try converter.setQueryItemAsURI( + in: &request, + style: .form, + explode: true, + name: "limit", + value: input.query.limit + ) + try converter.setQueryItemAsURI( + in: &request, + style: .form, + explode: true, + name: "habitat", + value: input.query.habitat + ) + try converter.setQueryItemAsURI( + in: &request, + style: .form, + explode: true, + name: "feeds", + value: input.query.feeds + ) + try converter.setHeaderFieldAsURI( + in: &request.headerFields, + name: "My-Request-UUID", + value: input.headers.My_hyphen_Request_hyphen_UUID + ) + try converter.setQueryItemAsURI( + in: &request, + style: .form, + explode: true, + name: "since", + value: input.query.since + ) + converter.setAcceptHeader( + in: &request.headerFields, + contentTypes: input.headers.accept + ) + return (request, nil) + }, + deserializer: { response, responseBody in + switch response.status.code { + case 200: + let headers: Operations.listPets.Output.Ok.Headers = .init( + My_hyphen_Response_hyphen_UUID: try converter.getRequiredHeaderFieldAsURI( + in: response.headerFields, + name: "My-Response-UUID", + as: Swift.String.self + ), + My_hyphen_Tracing_hyphen_Header: try converter.getOptionalHeaderFieldAsURI( + in: response.headerFields, + name: "My-Tracing-Header", + as: Components.Headers.TracingHeader.self + ) + ) + let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) + let body: Operations.listPets.Output.Ok.Body + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "application/json" + ] + ) + switch chosenContentType { + case "application/json": + body = try await converter.getResponseBodyAsJSON( + Components.Schemas.Pets.self, + from: responseBody, + transforming: { value in + .json(value) + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return .ok(.init( + headers: headers, + body: body + )) + default: + let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) + let body: Operations.listPets.Output.Default.Body + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "application/json" + ] + ) + switch chosenContentType { + case "application/json": + body = try await converter.getResponseBodyAsJSON( + Components.Schemas._Error.self, + from: responseBody, + transforming: { value in + .json(value) + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return .`default`( + statusCode: response.status.code, + .init(body: body) + ) + } + } + ) + } + /// Create a pet + /// + /// - Remark: HTTP `POST /pets`. + /// - Remark: Generated from `#/paths//pets/post(createPet)`. + public func createPet(_ input: Operations.createPet.Input) async throws -> Operations.createPet.Output { + try await client.send( + input: input, + forOperation: Operations.createPet.id, + serializer: { input in + let path = try converter.renderedPath( + template: "/pets", + parameters: [] + ) + var request: HTTPTypes.HTTPRequest = .init( + soar_path: path, + method: .post + ) + suppressMutabilityWarning(&request) + try converter.setHeaderFieldAsJSON( + in: &request.headerFields, + name: "X-Extra-Arguments", + value: input.headers.X_hyphen_Extra_hyphen_Arguments + ) + converter.setAcceptHeader( + in: &request.headerFields, + contentTypes: input.headers.accept + ) + let body: OpenAPIRuntime.HTTPBody? + switch input.body { + case let .json(value): + body = try converter.setRequiredRequestBodyAsJSON( + value, + headerFields: &request.headerFields, + contentType: "application/json; charset=utf-8" + ) + } + return (request, body) + }, + deserializer: { response, responseBody in + switch response.status.code { + case 201: + let headers: Operations.createPet.Output.Created.Headers = .init(X_hyphen_Extra_hyphen_Arguments: try converter.getOptionalHeaderFieldAsJSON( + in: response.headerFields, + name: "X-Extra-Arguments", + as: Components.Schemas.CodeError.self + )) + let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) + let body: Operations.createPet.Output.Created.Body + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "application/json" + ] + ) + switch chosenContentType { + case "application/json": + body = try await converter.getResponseBodyAsJSON( + Components.Schemas.Pet.self, + from: responseBody, + transforming: { value in + .json(value) + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return .created(.init( + headers: headers, + body: body + )) + case 400 ... 499: + let headers: Components.Responses.ErrorBadRequest.Headers = .init(X_hyphen_Reason: try converter.getOptionalHeaderFieldAsURI( + in: response.headerFields, + name: "X-Reason", + as: Swift.String.self + )) + let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) + let body: Components.Responses.ErrorBadRequest.Body + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "application/json" + ] + ) + switch chosenContentType { + case "application/json": + body = try await converter.getResponseBodyAsJSON( + Components.Responses.ErrorBadRequest.Body.jsonPayload.self, + from: responseBody, + transforming: { value in + .json(value) + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return .clientError( + statusCode: response.status.code, + .init( + headers: headers, + body: body + ) + ) + default: + return .undocumented( + statusCode: response.status.code, + .init( + headerFields: response.headerFields, + body: responseBody + ) + ) + } + } + ) + } + /// Create a pet using a url form + /// + /// - Remark: HTTP `POST /pets/create`. + /// - Remark: Generated from `#/paths//pets/create/post(createPetWithForm)`. + public func createPetWithForm(_ input: Operations.createPetWithForm.Input) async throws -> Operations.createPetWithForm.Output { + try await client.send( + input: input, + forOperation: Operations.createPetWithForm.id, + serializer: { input in + let path = try converter.renderedPath( + template: "/pets/create", + parameters: [] + ) + var request: HTTPTypes.HTTPRequest = .init( + soar_path: path, + method: .post + ) + suppressMutabilityWarning(&request) + let body: OpenAPIRuntime.HTTPBody? + switch input.body { + case let .urlEncodedForm(value): + body = try converter.setRequiredRequestBodyAsURLEncodedForm( + value, + headerFields: &request.headerFields, + contentType: "application/x-www-form-urlencoded" + ) + } + return (request, body) + }, + deserializer: { response, responseBody in + switch response.status.code { + case 204: + return .noContent(.init()) + default: + return .undocumented( + statusCode: response.status.code, + .init( + headerFields: response.headerFields, + body: responseBody + ) + ) + } + } + ) + } + /// - Remark: HTTP `GET /pets/stats`. + /// - Remark: Generated from `#/paths//pets/stats/get(getStats)`. + public func getStats(_ input: Operations.getStats.Input) async throws -> Operations.getStats.Output { + try await client.send( + input: input, + forOperation: Operations.getStats.id, + serializer: { input in + let path = try converter.renderedPath( + template: "/pets/stats", + parameters: [] + ) + var request: HTTPTypes.HTTPRequest = .init( + soar_path: path, + method: .get + ) + suppressMutabilityWarning(&request) + converter.setAcceptHeader( + in: &request.headerFields, + contentTypes: input.headers.accept + ) + return (request, nil) + }, + deserializer: { response, responseBody in + switch response.status.code { + case 200: + let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) + let body: Operations.getStats.Output.Ok.Body + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "application/json", + "text/plain", + "application/octet-stream" + ] + ) + switch chosenContentType { + case "application/json": + body = try await converter.getResponseBodyAsJSON( + Components.Schemas.PetStats.self, + from: responseBody, + transforming: { value in + .json(value) + } + ) + case "text/plain": + body = try converter.getResponseBodyAsBinary( + OpenAPIRuntime.HTTPBody.self, + from: responseBody, + transforming: { value in + .plainText(value) + } + ) + case "application/octet-stream": + body = try converter.getResponseBodyAsBinary( + OpenAPIRuntime.HTTPBody.self, + from: responseBody, + transforming: { value in + .binary(value) + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return .ok(.init(body: body)) + default: + return .undocumented( + statusCode: response.status.code, + .init( + headerFields: response.headerFields, + body: responseBody + ) + ) + } + } + ) + } + /// - Remark: HTTP `POST /pets/stats`. + /// - Remark: Generated from `#/paths//pets/stats/post(postStats)`. + public func postStats(_ input: Operations.postStats.Input) async throws -> Operations.postStats.Output { + try await client.send( + input: input, + forOperation: Operations.postStats.id, + serializer: { input in + let path = try converter.renderedPath( + template: "/pets/stats", + parameters: [] + ) + var request: HTTPTypes.HTTPRequest = .init( + soar_path: path, + method: .post + ) + suppressMutabilityWarning(&request) + let body: OpenAPIRuntime.HTTPBody? + switch input.body { + case let .json(value): + body = try converter.setRequiredRequestBodyAsJSON( + value, + headerFields: &request.headerFields, + contentType: "application/json; charset=utf-8" + ) + case let .plainText(value): + body = try converter.setRequiredRequestBodyAsBinary( + value, + headerFields: &request.headerFields, + contentType: "text/plain" + ) + case let .binary(value): + body = try converter.setRequiredRequestBodyAsBinary( + value, + headerFields: &request.headerFields, + contentType: "application/octet-stream" + ) + } + return (request, body) + }, + deserializer: { response, responseBody in + switch response.status.code { + case 202: + return .accepted(.init()) + default: + return .undocumented( + statusCode: response.status.code, + .init( + headerFields: response.headerFields, + body: responseBody + ) + ) + } + } + ) + } + /// - Remark: HTTP `POST /probe/`. + /// - Remark: Generated from `#/paths//probe//post(probe)`. + public func probe(_ input: Operations.probe.Input) async throws -> Operations.probe.Output { + try await client.send( + input: input, + forOperation: Operations.probe.id, + serializer: { input in + let path = try converter.renderedPath( + template: "/probe/", + parameters: [] + ) + var request: HTTPTypes.HTTPRequest = .init( + soar_path: path, + method: .post + ) + suppressMutabilityWarning(&request) + return (request, nil) + }, + deserializer: { response, responseBody in + switch response.status.code { + case 204: + return .noContent(.init()) + default: + return .undocumented( + statusCode: response.status.code, + .init( + headerFields: response.headerFields, + body: responseBody + ) + ) + } + } + ) + } + /// Update just a specific property of an existing pet. Nothing is updated if no request body is provided. + /// + /// - Remark: HTTP `PATCH /pets/{petId}`. + /// - Remark: Generated from `#/paths//pets/{petId}/patch(updatePet)`. + public func updatePet(_ input: Operations.updatePet.Input) async throws -> Operations.updatePet.Output { + try await client.send( + input: input, + forOperation: Operations.updatePet.id, + serializer: { input in + let path = try converter.renderedPath( + template: "/pets/{}", + parameters: [ + input.path.petId + ] + ) + var request: HTTPTypes.HTTPRequest = .init( + soar_path: path, + method: .patch + ) + suppressMutabilityWarning(&request) + converter.setAcceptHeader( + in: &request.headerFields, + contentTypes: input.headers.accept + ) + let body: OpenAPIRuntime.HTTPBody? + switch input.body { + case .none: + body = nil + case let .json(value): + body = try converter.setOptionalRequestBodyAsJSON( + value, + headerFields: &request.headerFields, + contentType: "application/json; charset=utf-8" + ) + } + return (request, body) + }, + deserializer: { response, responseBody in + switch response.status.code { + case 204: + return .noContent(.init()) + case 400: + let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) + let body: Operations.updatePet.Output.BadRequest.Body + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "application/json" + ] + ) + switch chosenContentType { + case "application/json": + body = try await converter.getResponseBodyAsJSON( + Operations.updatePet.Output.BadRequest.Body.jsonPayload.self, + from: responseBody, + transforming: { value in + .json(value) + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return .badRequest(.init(body: body)) + default: + return .undocumented( + statusCode: response.status.code, + .init( + headerFields: response.headerFields, + body: responseBody + ) + ) + } + } + ) + } + /// Upload an avatar + /// + /// - Remark: HTTP `PUT /pets/{petId}/avatar`. + /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)`. + public func uploadAvatarForPet(_ input: Operations.uploadAvatarForPet.Input) async throws -> Operations.uploadAvatarForPet.Output { + try await client.send( + input: input, + forOperation: Operations.uploadAvatarForPet.id, + serializer: { input in + let path = try converter.renderedPath( + template: "/pets/{}/avatar", + parameters: [ + input.path.petId + ] + ) + var request: HTTPTypes.HTTPRequest = .init( + soar_path: path, + method: .put + ) + suppressMutabilityWarning(&request) + converter.setAcceptHeader( + in: &request.headerFields, + contentTypes: input.headers.accept + ) + let body: OpenAPIRuntime.HTTPBody? + switch input.body { + case let .binary(value): + body = try converter.setRequiredRequestBodyAsBinary( + value, + headerFields: &request.headerFields, + contentType: "application/octet-stream" + ) + } + return (request, body) + }, + deserializer: { response, responseBody in + switch response.status.code { + case 200: + let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) + let body: Operations.uploadAvatarForPet.Output.Ok.Body + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "application/octet-stream" + ] + ) + switch chosenContentType { + case "application/octet-stream": + body = try converter.getResponseBodyAsBinary( + OpenAPIRuntime.HTTPBody.self, + from: responseBody, + transforming: { value in + .binary(value) + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return .ok(.init(body: body)) + case 412: + let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) + let body: Operations.uploadAvatarForPet.Output.PreconditionFailed.Body + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "application/json" + ] + ) + switch chosenContentType { + case "application/json": + body = try await converter.getResponseBodyAsJSON( + Swift.String.self, + from: responseBody, + transforming: { value in + .json(value) + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return .preconditionFailed(.init(body: body)) + case 500: + let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) + let body: Operations.uploadAvatarForPet.Output.InternalServerError.Body + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "text/plain" + ] + ) + switch chosenContentType { + case "text/plain": + body = try converter.getResponseBodyAsBinary( + OpenAPIRuntime.HTTPBody.self, + from: responseBody, + transforming: { value in + .plainText(value) + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return .internalServerError(.init(body: body)) + default: + return .undocumented( + statusCode: response.status.code, + .init( + headerFields: response.headerFields, + body: responseBody + ) + ) + } + } + ) + } + /// - Remark: HTTP `GET /pets/multipart-typed`. + /// - Remark: Generated from `#/paths//pets/multipart-typed/get(multipartDownloadTyped)`. + public func multipartDownloadTyped(_ input: Operations.multipartDownloadTyped.Input) async throws -> Operations.multipartDownloadTyped.Output { + try await client.send( + input: input, + forOperation: Operations.multipartDownloadTyped.id, + serializer: { input in + let path = try converter.renderedPath( + template: "/pets/multipart-typed", + parameters: [] + ) + var request: HTTPTypes.HTTPRequest = .init( + soar_path: path, + method: .get + ) + suppressMutabilityWarning(&request) + converter.setAcceptHeader( + in: &request.headerFields, + contentTypes: input.headers.accept + ) + return (request, nil) + }, + deserializer: { response, responseBody in + switch response.status.code { + case 200: + let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) + let body: Components.Responses.MultipartDownloadTypedResponse.Body + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "multipart/form-data" + ] + ) + switch chosenContentType { + case "multipart/form-data": + body = try converter.getResponseBodyAsMultipart( + OpenAPIRuntime.MultipartBody.self, + from: responseBody, + transforming: { value in + .multipartForm(value) + }, + boundary: contentType.requiredBoundary(), + allowsUnknownParts: true, + requiredExactlyOncePartNames: [ + "log" + ], + requiredAtLeastOncePartNames: [], + atMostOncePartNames: [ + "metadata" + ], + zeroOrMoreTimesPartNames: [ + "keyword" + ], + decoding: { part in + let headerFields = part.headerFields + let (name, filename) = try converter.extractContentDispositionNameAndFilename(in: headerFields) + switch name { + case "log": + let headers: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.logPayload.Headers = .init(x_hyphen_log_hyphen_type: try converter.getOptionalHeaderFieldAsURI( + in: headerFields, + name: "x-log-type", + as: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.logPayload.Headers.x_hyphen_log_hyphen_typePayload.self + )) + try converter.verifyContentTypeIfPresent( + in: headerFields, + matches: "text/plain" + ) + let body = try converter.getResponseBodyAsBinary( + OpenAPIRuntime.HTTPBody.self, + from: part.body, + transforming: { + $0 + } + ) + return .log(.init( + payload: .init( + headers: headers, + body: body + ), + filename: filename + )) + case "metadata": + try converter.verifyContentTypeIfPresent( + in: headerFields, + matches: "application/json" + ) + let body = try await converter.getResponseBodyAsJSON( + Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.metadataPayload.bodyPayload.self, + from: part.body, + transforming: { + $0 + } + ) + return .metadata(.init( + payload: .init(body: body), + filename: filename + )) + case "keyword": + try converter.verifyContentTypeIfPresent( + in: headerFields, + matches: "text/plain" + ) + let body = try converter.getResponseBodyAsBinary( + OpenAPIRuntime.HTTPBody.self, + from: part.body, + transforming: { + $0 + } + ) + return .keyword(.init( + payload: .init(body: body), + filename: filename + )) + default: + return .undocumented(part) + } + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return .ok(.init(body: body)) + default: + return .undocumented( + statusCode: response.status.code, + .init( + headerFields: response.headerFields, + body: responseBody + ) + ) + } + } + ) + } + /// - Remark: HTTP `POST /pets/multipart-typed`. + /// - Remark: Generated from `#/paths//pets/multipart-typed/post(multipartUploadTyped)`. + public func multipartUploadTyped(_ input: Operations.multipartUploadTyped.Input) async throws -> Operations.multipartUploadTyped.Output { + try await client.send( + input: input, + forOperation: Operations.multipartUploadTyped.id, + serializer: { input in + let path = try converter.renderedPath( + template: "/pets/multipart-typed", + parameters: [] + ) + var request: HTTPTypes.HTTPRequest = .init( + soar_path: path, + method: .post + ) + suppressMutabilityWarning(&request) + let body: OpenAPIRuntime.HTTPBody? + switch input.body { + case let .multipartForm(value): + body = try converter.setRequiredRequestBodyAsMultipart( + value, + headerFields: &request.headerFields, + contentType: "multipart/form-data", + allowsUnknownParts: true, + requiredExactlyOncePartNames: [ + "log" + ], + requiredAtLeastOncePartNames: [], + atMostOncePartNames: [ + "metadata" + ], + zeroOrMoreTimesPartNames: [ + "keyword" + ], + encoding: { part in + switch part { + case let .log(wrapped): + var headerFields: HTTPTypes.HTTPFields = .init() + let value = wrapped.payload + try converter.setHeaderFieldAsURI( + in: &headerFields, + name: "x-log-type", + value: value.headers.x_hyphen_log_hyphen_type + ) + let body = try converter.setRequiredRequestBodyAsBinary( + value.body, + headerFields: &headerFields, + contentType: "text/plain" + ) + return .init( + name: "log", + filename: wrapped.filename, + headerFields: headerFields, + body: body + ) + case let .metadata(wrapped): + var headerFields: HTTPTypes.HTTPFields = .init() + let value = wrapped.payload + let body = try converter.setRequiredRequestBodyAsJSON( + value.body, + headerFields: &headerFields, + contentType: "application/json; charset=utf-8" + ) + return .init( + name: "metadata", + filename: wrapped.filename, + headerFields: headerFields, + body: body + ) + case let .keyword(wrapped): + var headerFields: HTTPTypes.HTTPFields = .init() + let value = wrapped.payload + let body = try converter.setRequiredRequestBodyAsBinary( + value.body, + headerFields: &headerFields, + contentType: "text/plain" + ) + return .init( + name: "keyword", + filename: wrapped.filename, + headerFields: headerFields, + body: body + ) + case let .undocumented(value): + return value + } + } + ) + } + return (request, body) + }, + deserializer: { response, responseBody in + switch response.status.code { + case 202: + return .accepted(.init()) + default: + return .undocumented( + statusCode: response.status.code, + .init( + headerFields: response.headerFields, + body: responseBody + ) + ) + } + } + ) + } +} diff --git a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Server.swift b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Server.swift new file mode 100644 index 00000000..80d642b3 --- /dev/null +++ b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Server.swift @@ -0,0 +1,1015 @@ +// Generated by swift-openapi-generator, do not modify. +@_spi(Generated) import OpenAPIRuntime +#if os(Linux) +@preconcurrency import struct Foundation.URL +@preconcurrency import struct Foundation.Data +@preconcurrency import struct Foundation.Date +#else +import struct Foundation.URL +import struct Foundation.Data +import struct Foundation.Date +#endif +import HTTPTypes +extension APIProtocol { + /// Registers each operation handler with the provided transport. + /// - Parameters: + /// - transport: A transport to which to register the operation handlers. + /// - serverURL: A URL used to determine the path prefix for registered + /// request handlers. + /// - configuration: A set of configuration values for the server. + /// - middlewares: A list of middlewares to call before the handler. + public func registerHandlers( + on transport: any ServerTransport, + serverURL: Foundation.URL = .defaultOpenAPIServerURL, + configuration: Configuration = .init(), + middlewares: [any ServerMiddleware] = [] + ) throws { + let server = UniversalServer( + serverURL: serverURL, + handler: self, + configuration: configuration, + middlewares: middlewares + ) + try transport.register( + { + try await server.listPets( + request: $0, + body: $1, + metadata: $2 + ) + }, + method: .get, + path: server.apiPathComponentsWithServerPrefix("/pets") + ) + try transport.register( + { + try await server.createPet( + request: $0, + body: $1, + metadata: $2 + ) + }, + method: .post, + path: server.apiPathComponentsWithServerPrefix("/pets") + ) + try transport.register( + { + try await server.createPetWithForm( + request: $0, + body: $1, + metadata: $2 + ) + }, + method: .post, + path: server.apiPathComponentsWithServerPrefix("/pets/create") + ) + try transport.register( + { + try await server.getStats( + request: $0, + body: $1, + metadata: $2 + ) + }, + method: .get, + path: server.apiPathComponentsWithServerPrefix("/pets/stats") + ) + try transport.register( + { + try await server.postStats( + request: $0, + body: $1, + metadata: $2 + ) + }, + method: .post, + path: server.apiPathComponentsWithServerPrefix("/pets/stats") + ) + try transport.register( + { + try await server.probe( + request: $0, + body: $1, + metadata: $2 + ) + }, + method: .post, + path: server.apiPathComponentsWithServerPrefix("/probe/") + ) + try transport.register( + { + try await server.updatePet( + request: $0, + body: $1, + metadata: $2 + ) + }, + method: .patch, + path: server.apiPathComponentsWithServerPrefix("/pets/{petId}") + ) + try transport.register( + { + try await server.uploadAvatarForPet( + request: $0, + body: $1, + metadata: $2 + ) + }, + method: .put, + path: server.apiPathComponentsWithServerPrefix("/pets/{petId}/avatar") + ) + try transport.register( + { + try await server.multipartDownloadTyped( + request: $0, + body: $1, + metadata: $2 + ) + }, + method: .get, + path: server.apiPathComponentsWithServerPrefix("/pets/multipart-typed") + ) + try transport.register( + { + try await server.multipartUploadTyped( + request: $0, + body: $1, + metadata: $2 + ) + }, + method: .post, + path: server.apiPathComponentsWithServerPrefix("/pets/multipart-typed") + ) + } +} + +fileprivate extension UniversalServer where APIHandler: APIProtocol { + /// List all pets + /// + /// You can fetch + /// all the pets here + /// + /// - Remark: HTTP `GET /pets`. + /// - Remark: Generated from `#/paths//pets/get(listPets)`. + func listPets( + request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + try await handle( + request: request, + requestBody: body, + metadata: metadata, + forOperation: Operations.listPets.id, + using: { + APIHandler.listPets($0) + }, + deserializer: { request, requestBody, metadata in + let query: Operations.listPets.Input.Query = .init( + limit: try converter.getOptionalQueryItemAsURI( + in: request.soar_query, + style: .form, + explode: true, + name: "limit", + as: Swift.Int32.self + ), + habitat: try converter.getOptionalQueryItemAsURI( + in: request.soar_query, + style: .form, + explode: true, + name: "habitat", + as: Operations.listPets.Input.Query.habitatPayload.self + ), + feeds: try converter.getOptionalQueryItemAsURI( + in: request.soar_query, + style: .form, + explode: true, + name: "feeds", + as: Operations.listPets.Input.Query.feedsPayload.self + ), + since: try converter.getOptionalQueryItemAsURI( + in: request.soar_query, + style: .form, + explode: true, + name: "since", + as: Components.Parameters.query_period_born_hyphen_since.self + ) + ) + let headers: Operations.listPets.Input.Headers = .init( + My_hyphen_Request_hyphen_UUID: try converter.getOptionalHeaderFieldAsURI( + in: request.headerFields, + name: "My-Request-UUID", + as: Swift.String.self + ), + accept: try converter.extractAcceptHeaderIfPresent(in: request.headerFields) + ) + return Operations.listPets.Input( + query: query, + headers: headers + ) + }, + serializer: { output, request in + switch output { + case let .ok(value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: 200) + suppressMutabilityWarning(&response) + try converter.setHeaderFieldAsURI( + in: &response.headerFields, + name: "My-Response-UUID", + value: value.headers.My_hyphen_Response_hyphen_UUID + ) + try converter.setHeaderFieldAsURI( + in: &response.headerFields, + name: "My-Tracing-Header", + value: value.headers.My_hyphen_Tracing_hyphen_Header + ) + let body: OpenAPIRuntime.HTTPBody + switch value.body { + case let .json(value): + try converter.validateAcceptIfPresent( + "application/json", + in: request.headerFields + ) + body = try converter.setResponseBodyAsJSON( + value, + headerFields: &response.headerFields, + contentType: "application/json; charset=utf-8" + ) + } + return (response, body) + case let .`default`(statusCode, value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: statusCode) + suppressMutabilityWarning(&response) + let body: OpenAPIRuntime.HTTPBody + switch value.body { + case let .json(value): + try converter.validateAcceptIfPresent( + "application/json", + in: request.headerFields + ) + body = try converter.setResponseBodyAsJSON( + value, + headerFields: &response.headerFields, + contentType: "application/json; charset=utf-8" + ) + } + return (response, body) + } + } + ) + } + /// Create a pet + /// + /// - Remark: HTTP `POST /pets`. + /// - Remark: Generated from `#/paths//pets/post(createPet)`. + func createPet( + request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + try await handle( + request: request, + requestBody: body, + metadata: metadata, + forOperation: Operations.createPet.id, + using: { + APIHandler.createPet($0) + }, + deserializer: { request, requestBody, metadata in + let headers: Operations.createPet.Input.Headers = .init( + X_hyphen_Extra_hyphen_Arguments: try converter.getOptionalHeaderFieldAsJSON( + in: request.headerFields, + name: "X-Extra-Arguments", + as: Components.Schemas.CodeError.self + ), + accept: try converter.extractAcceptHeaderIfPresent(in: request.headerFields) + ) + let contentType = converter.extractContentTypeIfPresent(in: request.headerFields) + let body: Operations.createPet.Input.Body + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "application/json" + ] + ) + switch chosenContentType { + case "application/json": + body = try await converter.getRequiredRequestBodyAsJSON( + Components.Schemas.CreatePetRequest.self, + from: requestBody, + transforming: { value in + .json(value) + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return Operations.createPet.Input( + headers: headers, + body: body + ) + }, + serializer: { output, request in + switch output { + case let .created(value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: 201) + suppressMutabilityWarning(&response) + try converter.setHeaderFieldAsJSON( + in: &response.headerFields, + name: "X-Extra-Arguments", + value: value.headers.X_hyphen_Extra_hyphen_Arguments + ) + let body: OpenAPIRuntime.HTTPBody + switch value.body { + case let .json(value): + try converter.validateAcceptIfPresent( + "application/json", + in: request.headerFields + ) + body = try converter.setResponseBodyAsJSON( + value, + headerFields: &response.headerFields, + contentType: "application/json; charset=utf-8" + ) + } + return (response, body) + case let .clientError(statusCode, value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: statusCode) + suppressMutabilityWarning(&response) + try converter.setHeaderFieldAsURI( + in: &response.headerFields, + name: "X-Reason", + value: value.headers.X_hyphen_Reason + ) + let body: OpenAPIRuntime.HTTPBody + switch value.body { + case let .json(value): + try converter.validateAcceptIfPresent( + "application/json", + in: request.headerFields + ) + body = try converter.setResponseBodyAsJSON( + value, + headerFields: &response.headerFields, + contentType: "application/json; charset=utf-8" + ) + } + return (response, body) + case let .undocumented(statusCode, _): + return (.init(soar_statusCode: statusCode), nil) + } + } + ) + } + /// Create a pet using a url form + /// + /// - Remark: HTTP `POST /pets/create`. + /// - Remark: Generated from `#/paths//pets/create/post(createPetWithForm)`. + func createPetWithForm( + request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + try await handle( + request: request, + requestBody: body, + metadata: metadata, + forOperation: Operations.createPetWithForm.id, + using: { + APIHandler.createPetWithForm($0) + }, + deserializer: { request, requestBody, metadata in + let contentType = converter.extractContentTypeIfPresent(in: request.headerFields) + let body: Operations.createPetWithForm.Input.Body + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "application/x-www-form-urlencoded" + ] + ) + switch chosenContentType { + case "application/x-www-form-urlencoded": + body = try await converter.getRequiredRequestBodyAsURLEncodedForm( + Components.Schemas.CreatePetRequest.self, + from: requestBody, + transforming: { value in + .urlEncodedForm(value) + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return Operations.createPetWithForm.Input(body: body) + }, + serializer: { output, request in + switch output { + case let .noContent(value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: 204) + suppressMutabilityWarning(&response) + return (response, nil) + case let .undocumented(statusCode, _): + return (.init(soar_statusCode: statusCode), nil) + } + } + ) + } + /// - Remark: HTTP `GET /pets/stats`. + /// - Remark: Generated from `#/paths//pets/stats/get(getStats)`. + func getStats( + request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + try await handle( + request: request, + requestBody: body, + metadata: metadata, + forOperation: Operations.getStats.id, + using: { + APIHandler.getStats($0) + }, + deserializer: { request, requestBody, metadata in + let headers: Operations.getStats.Input.Headers = .init(accept: try converter.extractAcceptHeaderIfPresent(in: request.headerFields)) + return Operations.getStats.Input(headers: headers) + }, + serializer: { output, request in + switch output { + case let .ok(value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: 200) + suppressMutabilityWarning(&response) + let body: OpenAPIRuntime.HTTPBody + switch value.body { + case let .json(value): + try converter.validateAcceptIfPresent( + "application/json", + in: request.headerFields + ) + body = try converter.setResponseBodyAsJSON( + value, + headerFields: &response.headerFields, + contentType: "application/json; charset=utf-8" + ) + case let .plainText(value): + try converter.validateAcceptIfPresent( + "text/plain", + in: request.headerFields + ) + body = try converter.setResponseBodyAsBinary( + value, + headerFields: &response.headerFields, + contentType: "text/plain" + ) + case let .binary(value): + try converter.validateAcceptIfPresent( + "application/octet-stream", + in: request.headerFields + ) + body = try converter.setResponseBodyAsBinary( + value, + headerFields: &response.headerFields, + contentType: "application/octet-stream" + ) + } + return (response, body) + case let .undocumented(statusCode, _): + return (.init(soar_statusCode: statusCode), nil) + } + } + ) + } + /// - Remark: HTTP `POST /pets/stats`. + /// - Remark: Generated from `#/paths//pets/stats/post(postStats)`. + func postStats( + request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + try await handle( + request: request, + requestBody: body, + metadata: metadata, + forOperation: Operations.postStats.id, + using: { + APIHandler.postStats($0) + }, + deserializer: { request, requestBody, metadata in + let contentType = converter.extractContentTypeIfPresent(in: request.headerFields) + let body: Operations.postStats.Input.Body + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "application/json", + "text/plain", + "application/octet-stream" + ] + ) + switch chosenContentType { + case "application/json": + body = try await converter.getRequiredRequestBodyAsJSON( + Components.Schemas.PetStats.self, + from: requestBody, + transforming: { value in + .json(value) + } + ) + case "text/plain": + body = try converter.getRequiredRequestBodyAsBinary( + OpenAPIRuntime.HTTPBody.self, + from: requestBody, + transforming: { value in + .plainText(value) + } + ) + case "application/octet-stream": + body = try converter.getRequiredRequestBodyAsBinary( + OpenAPIRuntime.HTTPBody.self, + from: requestBody, + transforming: { value in + .binary(value) + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return Operations.postStats.Input(body: body) + }, + serializer: { output, request in + switch output { + case let .accepted(value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: 202) + suppressMutabilityWarning(&response) + return (response, nil) + case let .undocumented(statusCode, _): + return (.init(soar_statusCode: statusCode), nil) + } + } + ) + } + /// - Remark: HTTP `POST /probe/`. + /// - Remark: Generated from `#/paths//probe//post(probe)`. + func probe( + request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + try await handle( + request: request, + requestBody: body, + metadata: metadata, + forOperation: Operations.probe.id, + using: { + APIHandler.probe($0) + }, + deserializer: { request, requestBody, metadata in + return Operations.probe.Input() + }, + serializer: { output, request in + switch output { + case let .noContent(value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: 204) + suppressMutabilityWarning(&response) + return (response, nil) + case let .undocumented(statusCode, _): + return (.init(soar_statusCode: statusCode), nil) + } + } + ) + } + /// Update just a specific property of an existing pet. Nothing is updated if no request body is provided. + /// + /// - Remark: HTTP `PATCH /pets/{petId}`. + /// - Remark: Generated from `#/paths//pets/{petId}/patch(updatePet)`. + func updatePet( + request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + try await handle( + request: request, + requestBody: body, + metadata: metadata, + forOperation: Operations.updatePet.id, + using: { + APIHandler.updatePet($0) + }, + deserializer: { request, requestBody, metadata in + let path: Operations.updatePet.Input.Path = .init(petId: try converter.getPathParameterAsURI( + in: metadata.pathParameters, + name: "petId", + as: Swift.Int64.self + )) + let headers: Operations.updatePet.Input.Headers = .init(accept: try converter.extractAcceptHeaderIfPresent(in: request.headerFields)) + let contentType = converter.extractContentTypeIfPresent(in: request.headerFields) + let body: Components.RequestBodies.UpdatePetRequest? + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "application/json" + ] + ) + switch chosenContentType { + case "application/json": + body = try await converter.getOptionalRequestBodyAsJSON( + Components.RequestBodies.UpdatePetRequest.jsonPayload.self, + from: requestBody, + transforming: { value in + .json(value) + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return Operations.updatePet.Input( + path: path, + headers: headers, + body: body + ) + }, + serializer: { output, request in + switch output { + case let .noContent(value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: 204) + suppressMutabilityWarning(&response) + return (response, nil) + case let .badRequest(value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: 400) + suppressMutabilityWarning(&response) + let body: OpenAPIRuntime.HTTPBody + switch value.body { + case let .json(value): + try converter.validateAcceptIfPresent( + "application/json", + in: request.headerFields + ) + body = try converter.setResponseBodyAsJSON( + value, + headerFields: &response.headerFields, + contentType: "application/json; charset=utf-8" + ) + } + return (response, body) + case let .undocumented(statusCode, _): + return (.init(soar_statusCode: statusCode), nil) + } + } + ) + } + /// Upload an avatar + /// + /// - Remark: HTTP `PUT /pets/{petId}/avatar`. + /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)`. + func uploadAvatarForPet( + request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + try await handle( + request: request, + requestBody: body, + metadata: metadata, + forOperation: Operations.uploadAvatarForPet.id, + using: { + APIHandler.uploadAvatarForPet($0) + }, + deserializer: { request, requestBody, metadata in + let path: Operations.uploadAvatarForPet.Input.Path = .init(petId: try converter.getPathParameterAsURI( + in: metadata.pathParameters, + name: "petId", + as: Components.Parameters.path_period_petId.self + )) + let headers: Operations.uploadAvatarForPet.Input.Headers = .init(accept: try converter.extractAcceptHeaderIfPresent(in: request.headerFields)) + let contentType = converter.extractContentTypeIfPresent(in: request.headerFields) + let body: Operations.uploadAvatarForPet.Input.Body + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "application/octet-stream" + ] + ) + switch chosenContentType { + case "application/octet-stream": + body = try converter.getRequiredRequestBodyAsBinary( + OpenAPIRuntime.HTTPBody.self, + from: requestBody, + transforming: { value in + .binary(value) + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return Operations.uploadAvatarForPet.Input( + path: path, + headers: headers, + body: body + ) + }, + serializer: { output, request in + switch output { + case let .ok(value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: 200) + suppressMutabilityWarning(&response) + let body: OpenAPIRuntime.HTTPBody + switch value.body { + case let .binary(value): + try converter.validateAcceptIfPresent( + "application/octet-stream", + in: request.headerFields + ) + body = try converter.setResponseBodyAsBinary( + value, + headerFields: &response.headerFields, + contentType: "application/octet-stream" + ) + } + return (response, body) + case let .preconditionFailed(value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: 412) + suppressMutabilityWarning(&response) + let body: OpenAPIRuntime.HTTPBody + switch value.body { + case let .json(value): + try converter.validateAcceptIfPresent( + "application/json", + in: request.headerFields + ) + body = try converter.setResponseBodyAsJSON( + value, + headerFields: &response.headerFields, + contentType: "application/json; charset=utf-8" + ) + } + return (response, body) + case let .internalServerError(value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: 500) + suppressMutabilityWarning(&response) + let body: OpenAPIRuntime.HTTPBody + switch value.body { + case let .plainText(value): + try converter.validateAcceptIfPresent( + "text/plain", + in: request.headerFields + ) + body = try converter.setResponseBodyAsBinary( + value, + headerFields: &response.headerFields, + contentType: "text/plain" + ) + } + return (response, body) + case let .undocumented(statusCode, _): + return (.init(soar_statusCode: statusCode), nil) + } + } + ) + } + /// - Remark: HTTP `GET /pets/multipart-typed`. + /// - Remark: Generated from `#/paths//pets/multipart-typed/get(multipartDownloadTyped)`. + func multipartDownloadTyped( + request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + try await handle( + request: request, + requestBody: body, + metadata: metadata, + forOperation: Operations.multipartDownloadTyped.id, + using: { + APIHandler.multipartDownloadTyped($0) + }, + deserializer: { request, requestBody, metadata in + let headers: Operations.multipartDownloadTyped.Input.Headers = .init(accept: try converter.extractAcceptHeaderIfPresent(in: request.headerFields)) + return Operations.multipartDownloadTyped.Input(headers: headers) + }, + serializer: { output, request in + switch output { + case let .ok(value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: 200) + suppressMutabilityWarning(&response) + let body: OpenAPIRuntime.HTTPBody + switch value.body { + case let .multipartForm(value): + try converter.validateAcceptIfPresent( + "multipart/form-data", + in: request.headerFields + ) + body = try converter.setResponseBodyAsMultipart( + value, + headerFields: &response.headerFields, + contentType: "multipart/form-data", + allowsUnknownParts: true, + requiredExactlyOncePartNames: [ + "log" + ], + requiredAtLeastOncePartNames: [], + atMostOncePartNames: [ + "metadata" + ], + zeroOrMoreTimesPartNames: [ + "keyword" + ], + encoding: { part in + switch part { + case let .log(wrapped): + var headerFields: HTTPTypes.HTTPFields = .init() + let value = wrapped.payload + try converter.setHeaderFieldAsURI( + in: &headerFields, + name: "x-log-type", + value: value.headers.x_hyphen_log_hyphen_type + ) + let body = try converter.setResponseBodyAsBinary( + value.body, + headerFields: &headerFields, + contentType: "text/plain" + ) + return .init( + name: "log", + filename: wrapped.filename, + headerFields: headerFields, + body: body + ) + case let .metadata(wrapped): + var headerFields: HTTPTypes.HTTPFields = .init() + let value = wrapped.payload + let body = try converter.setResponseBodyAsJSON( + value.body, + headerFields: &headerFields, + contentType: "application/json; charset=utf-8" + ) + return .init( + name: "metadata", + filename: wrapped.filename, + headerFields: headerFields, + body: body + ) + case let .keyword(wrapped): + var headerFields: HTTPTypes.HTTPFields = .init() + let value = wrapped.payload + let body = try converter.setResponseBodyAsBinary( + value.body, + headerFields: &headerFields, + contentType: "text/plain" + ) + return .init( + name: "keyword", + filename: wrapped.filename, + headerFields: headerFields, + body: body + ) + case let .undocumented(value): + return value + } + } + ) + } + return (response, body) + case let .undocumented(statusCode, _): + return (.init(soar_statusCode: statusCode), nil) + } + } + ) + } + /// - Remark: HTTP `POST /pets/multipart-typed`. + /// - Remark: Generated from `#/paths//pets/multipart-typed/post(multipartUploadTyped)`. + func multipartUploadTyped( + request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + try await handle( + request: request, + requestBody: body, + metadata: metadata, + forOperation: Operations.multipartUploadTyped.id, + using: { + APIHandler.multipartUploadTyped($0) + }, + deserializer: { request, requestBody, metadata in + let contentType = converter.extractContentTypeIfPresent(in: request.headerFields) + let body: Components.RequestBodies.MultipartUploadTypedRequest + let chosenContentType = try converter.bestContentType( + received: contentType, + options: [ + "multipart/form-data" + ] + ) + switch chosenContentType { + case "multipart/form-data": + body = try converter.getRequiredRequestBodyAsMultipart( + OpenAPIRuntime.MultipartBody.self, + from: requestBody, + transforming: { value in + .multipartForm(value) + }, + boundary: contentType.requiredBoundary(), + allowsUnknownParts: true, + requiredExactlyOncePartNames: [ + "log" + ], + requiredAtLeastOncePartNames: [], + atMostOncePartNames: [ + "metadata" + ], + zeroOrMoreTimesPartNames: [ + "keyword" + ], + decoding: { part in + let headerFields = part.headerFields + let (name, filename) = try converter.extractContentDispositionNameAndFilename(in: headerFields) + switch name { + case "log": + let headers: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.logPayload.Headers = .init(x_hyphen_log_hyphen_type: try converter.getOptionalHeaderFieldAsURI( + in: headerFields, + name: "x-log-type", + as: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.logPayload.Headers.x_hyphen_log_hyphen_typePayload.self + )) + try converter.verifyContentTypeIfPresent( + in: headerFields, + matches: "text/plain" + ) + let body = try converter.getRequiredRequestBodyAsBinary( + OpenAPIRuntime.HTTPBody.self, + from: part.body, + transforming: { + $0 + } + ) + return .log(.init( + payload: .init( + headers: headers, + body: body + ), + filename: filename + )) + case "metadata": + try converter.verifyContentTypeIfPresent( + in: headerFields, + matches: "application/json" + ) + let body = try await converter.getRequiredRequestBodyAsJSON( + Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.metadataPayload.bodyPayload.self, + from: part.body, + transforming: { + $0 + } + ) + return .metadata(.init( + payload: .init(body: body), + filename: filename + )) + case "keyword": + try converter.verifyContentTypeIfPresent( + in: headerFields, + matches: "text/plain" + ) + let body = try converter.getRequiredRequestBodyAsBinary( + OpenAPIRuntime.HTTPBody.self, + from: part.body, + transforming: { + $0 + } + ) + return .keyword(.init( + payload: .init(body: body), + filename: filename + )) + default: + return .undocumented(part) + } + } + ) + default: + preconditionFailure("bestContentType chose an invalid content type.") + } + return Operations.multipartUploadTyped.Input(body: body) + }, + serializer: { output, request in + switch output { + case let .accepted(value): + suppressUnusedWarning(value) + var response = HTTPTypes.HTTPResponse(soar_statusCode: 202) + suppressMutabilityWarning(&response) + return (response, nil) + case let .undocumented(statusCode, _): + return (.init(soar_statusCode: statusCode), nil) + } + } + ) + } +} diff --git a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Types.swift b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Types.swift new file mode 100644 index 00000000..608dc287 --- /dev/null +++ b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Types.swift @@ -0,0 +1,3071 @@ +// Generated by swift-openapi-generator, do not modify. +@_spi(Generated) import OpenAPIRuntime +#if os(Linux) +@preconcurrency import struct Foundation.URL +@preconcurrency import struct Foundation.Data +@preconcurrency import struct Foundation.Date +#else +import struct Foundation.URL +import struct Foundation.Data +import struct Foundation.Date +#endif +/// A type that performs HTTP operations defined by the OpenAPI document. +public protocol APIProtocol: Sendable { + /// List all pets + /// + /// You can fetch + /// all the pets here + /// + /// - Remark: HTTP `GET /pets`. + /// - Remark: Generated from `#/paths//pets/get(listPets)`. + func listPets(_ input: Operations.listPets.Input) async throws -> Operations.listPets.Output + /// Create a pet + /// + /// - Remark: HTTP `POST /pets`. + /// - Remark: Generated from `#/paths//pets/post(createPet)`. + func createPet(_ input: Operations.createPet.Input) async throws -> Operations.createPet.Output + /// Create a pet using a url form + /// + /// - Remark: HTTP `POST /pets/create`. + /// - Remark: Generated from `#/paths//pets/create/post(createPetWithForm)`. + func createPetWithForm(_ input: Operations.createPetWithForm.Input) async throws -> Operations.createPetWithForm.Output + /// - Remark: HTTP `GET /pets/stats`. + /// - Remark: Generated from `#/paths//pets/stats/get(getStats)`. + func getStats(_ input: Operations.getStats.Input) async throws -> Operations.getStats.Output + /// - Remark: HTTP `POST /pets/stats`. + /// - Remark: Generated from `#/paths//pets/stats/post(postStats)`. + func postStats(_ input: Operations.postStats.Input) async throws -> Operations.postStats.Output + /// - Remark: HTTP `POST /probe/`. + /// - Remark: Generated from `#/paths//probe//post(probe)`. + func probe(_ input: Operations.probe.Input) async throws -> Operations.probe.Output + /// Update just a specific property of an existing pet. Nothing is updated if no request body is provided. + /// + /// - Remark: HTTP `PATCH /pets/{petId}`. + /// - Remark: Generated from `#/paths//pets/{petId}/patch(updatePet)`. + func updatePet(_ input: Operations.updatePet.Input) async throws -> Operations.updatePet.Output + /// Upload an avatar + /// + /// - Remark: HTTP `PUT /pets/{petId}/avatar`. + /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)`. + func uploadAvatarForPet(_ input: Operations.uploadAvatarForPet.Input) async throws -> Operations.uploadAvatarForPet.Output + /// - Remark: HTTP `GET /pets/multipart-typed`. + /// - Remark: Generated from `#/paths//pets/multipart-typed/get(multipartDownloadTyped)`. + func multipartDownloadTyped(_ input: Operations.multipartDownloadTyped.Input) async throws -> Operations.multipartDownloadTyped.Output + /// - Remark: HTTP `POST /pets/multipart-typed`. + /// - Remark: Generated from `#/paths//pets/multipart-typed/post(multipartUploadTyped)`. + func multipartUploadTyped(_ input: Operations.multipartUploadTyped.Input) async throws -> Operations.multipartUploadTyped.Output +} + +/// Convenience overloads for operation inputs. +extension APIProtocol { + /// List all pets + /// + /// You can fetch + /// all the pets here + /// + /// - Remark: HTTP `GET /pets`. + /// - Remark: Generated from `#/paths//pets/get(listPets)`. + public func listPets( + query: Operations.listPets.Input.Query = .init(), + headers: Operations.listPets.Input.Headers = .init() + ) async throws -> Operations.listPets.Output { + try await listPets(Operations.listPets.Input( + query: query, + headers: headers + )) + } + /// Create a pet + /// + /// - Remark: HTTP `POST /pets`. + /// - Remark: Generated from `#/paths//pets/post(createPet)`. + public func createPet( + headers: Operations.createPet.Input.Headers = .init(), + body: Operations.createPet.Input.Body + ) async throws -> Operations.createPet.Output { + try await createPet(Operations.createPet.Input( + headers: headers, + body: body + )) + } + /// Create a pet using a url form + /// + /// - Remark: HTTP `POST /pets/create`. + /// - Remark: Generated from `#/paths//pets/create/post(createPetWithForm)`. + public func createPetWithForm(body: Operations.createPetWithForm.Input.Body) async throws -> Operations.createPetWithForm.Output { + try await createPetWithForm(Operations.createPetWithForm.Input(body: body)) + } + /// - Remark: HTTP `GET /pets/stats`. + /// - Remark: Generated from `#/paths//pets/stats/get(getStats)`. + public func getStats(headers: Operations.getStats.Input.Headers = .init()) async throws -> Operations.getStats.Output { + try await getStats(Operations.getStats.Input(headers: headers)) + } + /// - Remark: HTTP `POST /pets/stats`. + /// - Remark: Generated from `#/paths//pets/stats/post(postStats)`. + public func postStats(body: Operations.postStats.Input.Body) async throws -> Operations.postStats.Output { + try await postStats(Operations.postStats.Input(body: body)) + } + /// - Remark: HTTP `POST /probe/`. + /// - Remark: Generated from `#/paths//probe//post(probe)`. + public func probe() async throws -> Operations.probe.Output { + try await probe(Operations.probe.Input()) + } + /// Update just a specific property of an existing pet. Nothing is updated if no request body is provided. + /// + /// - Remark: HTTP `PATCH /pets/{petId}`. + /// - Remark: Generated from `#/paths//pets/{petId}/patch(updatePet)`. + public func updatePet( + path: Operations.updatePet.Input.Path, + headers: Operations.updatePet.Input.Headers = .init(), + body: Components.RequestBodies.UpdatePetRequest? = nil + ) async throws -> Operations.updatePet.Output { + try await updatePet(Operations.updatePet.Input( + path: path, + headers: headers, + body: body + )) + } + /// Upload an avatar + /// + /// - Remark: HTTP `PUT /pets/{petId}/avatar`. + /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)`. + public func uploadAvatarForPet( + path: Operations.uploadAvatarForPet.Input.Path, + headers: Operations.uploadAvatarForPet.Input.Headers = .init(), + body: Operations.uploadAvatarForPet.Input.Body + ) async throws -> Operations.uploadAvatarForPet.Output { + try await uploadAvatarForPet(Operations.uploadAvatarForPet.Input( + path: path, + headers: headers, + body: body + )) + } + /// - Remark: HTTP `GET /pets/multipart-typed`. + /// - Remark: Generated from `#/paths//pets/multipart-typed/get(multipartDownloadTyped)`. + public func multipartDownloadTyped(headers: Operations.multipartDownloadTyped.Input.Headers = .init()) async throws -> Operations.multipartDownloadTyped.Output { + try await multipartDownloadTyped(Operations.multipartDownloadTyped.Input(headers: headers)) + } + /// - Remark: HTTP `POST /pets/multipart-typed`. + /// - Remark: Generated from `#/paths//pets/multipart-typed/post(multipartUploadTyped)`. + public func multipartUploadTyped(body: Components.RequestBodies.MultipartUploadTypedRequest) async throws -> Operations.multipartUploadTyped.Output { + try await multipartUploadTyped(Operations.multipartUploadTyped.Input(body: body)) + } +} + +/// Server URLs defined in the OpenAPI document. +public enum Servers { + /// Server URL variables defined in the OpenAPI document. + public enum Variables { + /// The variables for Server3 defined in the OpenAPI document. + public enum Server3 { + /// The "port" variable defined in the OpenAPI document. The default value is "443". + @frozen public enum Port: Swift.String { + case _443 = "443" + case _8443 = "8443" + /// The default variable. + public static var `default`: Port { + return Port._443 + } + } + } + } + /// Example Petstore implementation service + public static func server1() throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://example.com/api", + variables: [] + ) + } + public static func server2() throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "/api", + variables: [] + ) + } + /// A custom domain. + /// + /// - Parameters: + /// - _protocol: + /// - subdomain: A subdomain name. + /// - port: + /// - basePath: The base API path. + public static func server3( + _protocol: Swift.String = "https", + subdomain: Swift.String = "test", + port: Variables.Server3.Port = Variables.Server3.Port.default, + basePath: Swift.String = "v1" + ) throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "{protocol}://{subdomain}.example.com:{port}/{basePath}", + variables: [ + .init( + name: "protocol", + value: _protocol + ), + .init( + name: "subdomain", + value: subdomain + ), + .init( + name: "port", + value: port.rawValue + ), + .init( + name: "basePath", + value: basePath + ) + ] + ) + } +} + +/// Types generated from the components section of the OpenAPI document. +public enum Components { + /// Types generated from the `#/components/schemas` section of the OpenAPI document. + public enum Schemas { + /// Pet metadata + /// + /// - Remark: Generated from `#/components/schemas/Pet`. + public struct Pet: Codable, Hashable, Sendable { + /// Pet id + /// + /// - Remark: Generated from `#/components/schemas/Pet/id`. + public var id: Swift.Int64 + /// Pet name + /// + /// - Remark: Generated from `#/components/schemas/Pet/name`. + public var name: Swift.String + /// - Remark: Generated from `#/components/schemas/Pet/tag`. + public var tag: Swift.String? + /// Pet genome (base64-encoded) + /// + /// - Remark: Generated from `#/components/schemas/Pet/genome`. + public var genome: OpenAPIRuntime.Base64EncodedData? + /// - Remark: Generated from `#/components/schemas/Pet/kind`. + public var kind: Components.Schemas.PetKind? + /// Creates a new `Pet`. + /// + /// - Parameters: + /// - id: Pet id + /// - name: Pet name + /// - tag: + /// - genome: Pet genome (base64-encoded) + /// - kind: + public init( + id: Swift.Int64, + name: Swift.String, + tag: Swift.String? = nil, + genome: OpenAPIRuntime.Base64EncodedData? = nil, + kind: Components.Schemas.PetKind? = nil + ) { + self.id = id + self.name = name + self.tag = tag + self.genome = genome + self.kind = kind + } + public enum CodingKeys: String, CodingKey { + case id + case name + case tag + case genome + case kind + } + } + /// - Remark: Generated from `#/components/schemas/MixedAnyOf`. + public struct MixedAnyOf: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/MixedAnyOf/value1`. + public var value1: Foundation.Date? + /// - Remark: Generated from `#/components/schemas/MixedAnyOf/value2`. + public var value2: Components.Schemas.PetKind? + /// - Remark: Generated from `#/components/schemas/MixedAnyOf/value3`. + public var value3: Components.Schemas.Pet? + /// - Remark: Generated from `#/components/schemas/MixedAnyOf/value4`. + public var value4: Swift.String? + /// Creates a new `MixedAnyOf`. + /// + /// - Parameters: + /// - value1: + /// - value2: + /// - value3: + /// - value4: + public init( + value1: Foundation.Date? = nil, + value2: Components.Schemas.PetKind? = nil, + value3: Components.Schemas.Pet? = nil, + value4: Swift.String? = nil + ) { + self.value1 = value1 + self.value2 = value2 + self.value3 = value3 + self.value4 = value4 + } + public init(from decoder: any Decoder) throws { + var errors: [any Error] = [] + do { + value1 = try decoder.decodeFromSingleValueContainer() + } catch { + errors.append(error) + } + do { + value2 = try decoder.decodeFromSingleValueContainer() + } catch { + errors.append(error) + } + do { + value3 = try .init(from: decoder) + } catch { + errors.append(error) + } + do { + value4 = try decoder.decodeFromSingleValueContainer() + } catch { + errors.append(error) + } + try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( + [ + value1, + value2, + value3, + value4 + ], + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) + } + public func encode(to encoder: any Encoder) throws { + try encoder.encodeFirstNonNilValueToSingleValueContainer([ + value1, + value2, + value4 + ]) + try value3?.encode(to: encoder) + } + } + /// - Remark: Generated from `#/components/schemas/MixedOneOf`. + @frozen public enum MixedOneOf: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/MixedOneOf/case1`. + case case1(Foundation.Date) + /// - Remark: Generated from `#/components/schemas/MixedOneOf/case2`. + case PetKind(Components.Schemas.PetKind) + /// - Remark: Generated from `#/components/schemas/MixedOneOf/case3`. + case Pet(Components.Schemas.Pet) + public init(from decoder: any Decoder) throws { + var errors: [any Error] = [] + do { + self = .case1(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + do { + self = .PetKind(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + do { + self = .Pet(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + throw Swift.DecodingError.failedToDecodeOneOfSchema( + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) + } + public func encode(to encoder: any Encoder) throws { + switch self { + case let .case1(value): + try encoder.encodeToSingleValueContainer(value) + case let .PetKind(value): + try encoder.encodeToSingleValueContainer(value) + case let .Pet(value): + try value.encode(to: encoder) + } + } + } + /// - Remark: Generated from `#/components/schemas/MixedAllOfPrimitive`. + public struct MixedAllOfPrimitive: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/MixedAllOfPrimitive/value1`. + public var value1: Foundation.Date + /// - Remark: Generated from `#/components/schemas/MixedAllOfPrimitive/value2`. + public var value2: Swift.String + /// Creates a new `MixedAllOfPrimitive`. + /// + /// - Parameters: + /// - value1: + /// - value2: + public init( + value1: Foundation.Date, + value2: Swift.String + ) { + self.value1 = value1 + self.value2 = value2 + } + public init(from decoder: any Decoder) throws { + value1 = try decoder.decodeFromSingleValueContainer() + value2 = try decoder.decodeFromSingleValueContainer() + } + public func encode(to encoder: any Encoder) throws { + try encoder.encodeToSingleValueContainer(value1) + } + } + /// Kind of pet + /// + /// - Remark: Generated from `#/components/schemas/PetKind`. + @frozen public enum PetKind: String, Codable, Hashable, Sendable, CaseIterable { + case cat = "cat" + case dog = "dog" + case ELEPHANT = "ELEPHANT" + case BIG_ELEPHANT_1 = "BIG_ELEPHANT_1" + case _dollar_nake = "$nake" + case _public = "public" + } + /// - Remark: Generated from `#/components/schemas/CreatePetRequest`. + public struct CreatePetRequest: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/CreatePetRequest/name`. + public var name: Swift.String + /// - Remark: Generated from `#/components/schemas/CreatePetRequest/kind`. + public var kind: Components.Schemas.PetKind? + /// - Remark: Generated from `#/components/schemas/CreatePetRequest/tag`. + public var tag: Swift.String? + /// - Remark: Generated from `#/components/schemas/CreatePetRequest/genome`. + public var genome: OpenAPIRuntime.Base64EncodedData? + /// Creates a new `CreatePetRequest`. + /// + /// - Parameters: + /// - name: + /// - kind: + /// - tag: + /// - genome: + public init( + name: Swift.String, + kind: Components.Schemas.PetKind? = nil, + tag: Swift.String? = nil, + genome: OpenAPIRuntime.Base64EncodedData? = nil + ) { + self.name = name + self.kind = kind + self.tag = tag + self.genome = genome + } + public enum CodingKeys: String, CodingKey { + case name + case kind + case tag + case genome + } + } + /// - Remark: Generated from `#/components/schemas/Pets`. + public typealias Pets = [Components.Schemas.Pet] + /// - Remark: Generated from `#/components/schemas/Error`. + public struct _Error: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/Error/code`. + public var code: Swift.Int32 + /// - Remark: Generated from `#/components/schemas/Error/me$sage`. + public var me_dollar_sage: Swift.String + /// Extra information about the error. + /// + /// - Remark: Generated from `#/components/schemas/Error/extraInfo`. + public var extraInfo: Components.Schemas.ExtraInfo? + /// Custom user-provided key-value pairs. + /// + /// - Remark: Generated from `#/components/schemas/Error/userData`. + public var userData: OpenAPIRuntime.OpenAPIObjectContainer? + /// Creates a new `_Error`. + /// + /// - Parameters: + /// - code: + /// - me_dollar_sage: + /// - extraInfo: Extra information about the error. + /// - userData: Custom user-provided key-value pairs. + public init( + code: Swift.Int32, + me_dollar_sage: Swift.String, + extraInfo: Components.Schemas.ExtraInfo? = nil, + userData: OpenAPIRuntime.OpenAPIObjectContainer? = nil + ) { + self.code = code + self.me_dollar_sage = me_dollar_sage + self.extraInfo = extraInfo + self.userData = userData + } + public enum CodingKeys: String, CodingKey { + case code + case me_dollar_sage = "me$sage" + case extraInfo + case userData + } + } + /// - Remark: Generated from `#/components/schemas/PetFeeding`. + public struct PetFeeding: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/PetFeeding/schedule`. + @frozen public enum schedulePayload: String, Codable, Hashable, Sendable, CaseIterable { + case hourly = "hourly" + case daily = "daily" + case weekly = "weekly" + } + /// - Remark: Generated from `#/components/schemas/PetFeeding/schedule`. + public var schedule: Components.Schemas.PetFeeding.schedulePayload? + /// Creates a new `PetFeeding`. + /// + /// - Parameters: + /// - schedule: + public init(schedule: Components.Schemas.PetFeeding.schedulePayload? = nil) { + self.schedule = schedule + } + public enum CodingKeys: String, CodingKey { + case schedule + } + } + /// - Remark: Generated from `#/components/schemas/DOB`. + public typealias DOB = Foundation.Date + /// - Remark: Generated from `#/components/schemas/ExtraInfo`. + public typealias ExtraInfo = Swift.String + /// - Remark: Generated from `#/components/schemas/NoAdditionalProperties`. + public struct NoAdditionalProperties: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/NoAdditionalProperties/foo`. + public var foo: Swift.String? + /// Creates a new `NoAdditionalProperties`. + /// + /// - Parameters: + /// - foo: + public init(foo: Swift.String? = nil) { + self.foo = foo + } + public enum CodingKeys: String, CodingKey { + case foo + } + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + foo = try container.decodeIfPresent( + Swift.String.self, + forKey: .foo + ) + try decoder.ensureNoAdditionalProperties(knownKeys: [ + "foo" + ]) + } + } + /// - Remark: Generated from `#/components/schemas/AnyAdditionalProperties`. + public struct AnyAdditionalProperties: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/AnyAdditionalProperties/foo`. + public var foo: Swift.String? + /// A container of undocumented properties. + public var additionalProperties: OpenAPIRuntime.OpenAPIObjectContainer + /// Creates a new `AnyAdditionalProperties`. + /// + /// - Parameters: + /// - foo: + /// - additionalProperties: A container of undocumented properties. + public init( + foo: Swift.String? = nil, + additionalProperties: OpenAPIRuntime.OpenAPIObjectContainer = .init() + ) { + self.foo = foo + self.additionalProperties = additionalProperties + } + public enum CodingKeys: String, CodingKey { + case foo + } + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + foo = try container.decodeIfPresent( + Swift.String.self, + forKey: .foo + ) + additionalProperties = try decoder.decodeAdditionalProperties(knownKeys: [ + "foo" + ]) + } + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent( + foo, + forKey: .foo + ) + try encoder.encodeAdditionalProperties(additionalProperties) + } + } + /// - Remark: Generated from `#/components/schemas/TypedAdditionalProperties`. + public struct TypedAdditionalProperties: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/TypedAdditionalProperties/foo`. + public var foo: Swift.String? + /// A container of undocumented properties. + public var additionalProperties: [String: Swift.Int] + /// Creates a new `TypedAdditionalProperties`. + /// + /// - Parameters: + /// - foo: + /// - additionalProperties: A container of undocumented properties. + public init( + foo: Swift.String? = nil, + additionalProperties: [String: Swift.Int] = .init() + ) { + self.foo = foo + self.additionalProperties = additionalProperties + } + public enum CodingKeys: String, CodingKey { + case foo + } + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + foo = try container.decodeIfPresent( + Swift.String.self, + forKey: .foo + ) + additionalProperties = try decoder.decodeAdditionalProperties(knownKeys: [ + "foo" + ]) + } + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent( + foo, + forKey: .foo + ) + try encoder.encodeAdditionalProperties(additionalProperties) + } + } + /// - Remark: Generated from `#/components/schemas/ObjectWithOptionalNullableArrayOfNullableItems`. + public struct ObjectWithOptionalNullableArrayOfNullableItems: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/ObjectWithOptionalNullableArrayOfNullableItems/foo`. + public var foo: [Swift.String?]? + /// Creates a new `ObjectWithOptionalNullableArrayOfNullableItems`. + /// + /// - Parameters: + /// - foo: + public init(foo: [Swift.String?]? = nil) { + self.foo = foo + } + public enum CodingKeys: String, CodingKey { + case foo + } + } + /// - Remark: Generated from `#/components/schemas/CodeError`. + public struct CodeError: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/CodeError/code`. + public var code: Swift.Int + /// Creates a new `CodeError`. + /// + /// - Parameters: + /// - code: + public init(code: Swift.Int) { + self.code = code + } + public enum CodingKeys: String, CodingKey { + case code + } + } + /// - Remark: Generated from `#/components/schemas/AllOfObjects`. + public struct AllOfObjects: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/AllOfObjects/value1`. + public struct Value1Payload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/AllOfObjects/value1/message`. + public var message: Swift.String + /// Creates a new `Value1Payload`. + /// + /// - Parameters: + /// - message: + public init(message: Swift.String) { + self.message = message + } + public enum CodingKeys: String, CodingKey { + case message + } + } + /// - Remark: Generated from `#/components/schemas/AllOfObjects/value1`. + public var value1: Components.Schemas.AllOfObjects.Value1Payload + /// - Remark: Generated from `#/components/schemas/AllOfObjects/value2`. + public var value2: Components.Schemas.CodeError + /// Creates a new `AllOfObjects`. + /// + /// - Parameters: + /// - value1: + /// - value2: + public init( + value1: Components.Schemas.AllOfObjects.Value1Payload, + value2: Components.Schemas.CodeError + ) { + self.value1 = value1 + self.value2 = value2 + } + public init(from decoder: any Decoder) throws { + value1 = try .init(from: decoder) + value2 = try .init(from: decoder) + } + public func encode(to encoder: any Encoder) throws { + try value1.encode(to: encoder) + try value2.encode(to: encoder) + } + } + /// - Remark: Generated from `#/components/schemas/AnyOfObjects`. + public struct AnyOfObjects: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/AnyOfObjects/value1`. + public struct Value1Payload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/AnyOfObjects/value1/message`. + public var message: Swift.String + /// Creates a new `Value1Payload`. + /// + /// - Parameters: + /// - message: + public init(message: Swift.String) { + self.message = message + } + public enum CodingKeys: String, CodingKey { + case message + } + } + /// - Remark: Generated from `#/components/schemas/AnyOfObjects/value1`. + public var value1: Components.Schemas.AnyOfObjects.Value1Payload? + /// - Remark: Generated from `#/components/schemas/AnyOfObjects/value2`. + public var value2: Components.Schemas.CodeError? + /// Creates a new `AnyOfObjects`. + /// + /// - Parameters: + /// - value1: + /// - value2: + public init( + value1: Components.Schemas.AnyOfObjects.Value1Payload? = nil, + value2: Components.Schemas.CodeError? = nil + ) { + self.value1 = value1 + self.value2 = value2 + } + public init(from decoder: any Decoder) throws { + var errors: [any Error] = [] + do { + value1 = try .init(from: decoder) + } catch { + errors.append(error) + } + do { + value2 = try .init(from: decoder) + } catch { + errors.append(error) + } + try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( + [ + value1, + value2 + ], + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) + } + public func encode(to encoder: any Encoder) throws { + try value1?.encode(to: encoder) + try value2?.encode(to: encoder) + } + } + /// - Remark: Generated from `#/components/schemas/OneOfAny`. + @frozen public enum OneOfAny: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/OneOfAny/case1`. + case case1(Swift.String) + /// - Remark: Generated from `#/components/schemas/OneOfAny/case2`. + case case2(Swift.Int) + /// - Remark: Generated from `#/components/schemas/OneOfAny/case3`. + case CodeError(Components.Schemas.CodeError) + /// - Remark: Generated from `#/components/schemas/OneOfAny/case4`. + public struct Case4Payload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/OneOfAny/case4/message`. + public var message: Swift.String + /// Creates a new `Case4Payload`. + /// + /// - Parameters: + /// - message: + public init(message: Swift.String) { + self.message = message + } + public enum CodingKeys: String, CodingKey { + case message + } + } + /// - Remark: Generated from `#/components/schemas/OneOfAny/case4`. + case case4(Components.Schemas.OneOfAny.Case4Payload) + public init(from decoder: any Decoder) throws { + var errors: [any Error] = [] + do { + self = .case1(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + do { + self = .case2(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + do { + self = .CodeError(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .case4(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + throw Swift.DecodingError.failedToDecodeOneOfSchema( + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) + } + public func encode(to encoder: any Encoder) throws { + switch self { + case let .case1(value): + try encoder.encodeToSingleValueContainer(value) + case let .case2(value): + try encoder.encodeToSingleValueContainer(value) + case let .CodeError(value): + try value.encode(to: encoder) + case let .case4(value): + try value.encode(to: encoder) + } + } + } + /// - Remark: Generated from `#/components/schemas/PetExercise`. + public struct PetExercise: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/PetExercise/kind`. + public var kind: Swift.String + /// Creates a new `PetExercise`. + /// + /// - Parameters: + /// - kind: + public init(kind: Swift.String) { + self.kind = kind + } + public enum CodingKeys: String, CodingKey { + case kind + } + } + /// - Remark: Generated from `#/components/schemas/Walk`. + public struct Walk: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/Walk/kind`. + public var kind: Swift.String + /// - Remark: Generated from `#/components/schemas/Walk/length`. + public var length: Swift.Int + /// Creates a new `Walk`. + /// + /// - Parameters: + /// - kind: + /// - length: + public init( + kind: Swift.String, + length: Swift.Int + ) { + self.kind = kind + self.length = length + } + public enum CodingKeys: String, CodingKey { + case kind + case length + } + } + /// - Remark: Generated from `#/components/schemas/MessagedExercise`. + public struct MessagedExercise: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/MessagedExercise/value1`. + public var value1: Components.Schemas.PetExercise + /// - Remark: Generated from `#/components/schemas/MessagedExercise/value2`. + public struct Value2Payload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/MessagedExercise/value2/message`. + public var message: Swift.String + /// Creates a new `Value2Payload`. + /// + /// - Parameters: + /// - message: + public init(message: Swift.String) { + self.message = message + } + public enum CodingKeys: String, CodingKey { + case message + } + } + /// - Remark: Generated from `#/components/schemas/MessagedExercise/value2`. + public var value2: Components.Schemas.MessagedExercise.Value2Payload + /// Creates a new `MessagedExercise`. + /// + /// - Parameters: + /// - value1: + /// - value2: + public init( + value1: Components.Schemas.PetExercise, + value2: Components.Schemas.MessagedExercise.Value2Payload + ) { + self.value1 = value1 + self.value2 = value2 + } + public init(from decoder: any Decoder) throws { + value1 = try .init(from: decoder) + value2 = try .init(from: decoder) + } + public func encode(to encoder: any Encoder) throws { + try value1.encode(to: encoder) + try value2.encode(to: encoder) + } + } + /// - Remark: Generated from `#/components/schemas/OneOfObjectsWithDiscriminator`. + @frozen public enum OneOfObjectsWithDiscriminator: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/OneOfObjectsWithDiscriminator/Walk`. + case Walk(Components.Schemas.Walk) + /// - Remark: Generated from `#/components/schemas/OneOfObjectsWithDiscriminator/MessagedExercise`. + case MessagedExercise(Components.Schemas.MessagedExercise) + public enum CodingKeys: String, CodingKey { + case kind + } + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: .kind + ) + switch discriminator { + case "Walk", "#/components/schemas/Walk": + self = .Walk(try .init(from: decoder)) + case "MessagedExercise", "#/components/schemas/MessagedExercise": + self = .MessagedExercise(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys.kind, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Encoder) throws { + switch self { + case let .Walk(value): + try value.encode(to: encoder) + case let .MessagedExercise(value): + try value.encode(to: encoder) + } + } + } + /// - Remark: Generated from `#/components/schemas/PetStats`. + public struct PetStats: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/PetStats/count`. + public var count: Swift.Int + /// Creates a new `PetStats`. + /// + /// - Parameters: + /// - count: + public init(count: Swift.Int) { + self.count = count + } + public enum CodingKeys: String, CodingKey { + case count + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePet`. + public struct RecursivePet: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePet/name`. + public var name: Swift.String { + get { + storage.value.name + } + _modify { + yield &storage.value.name + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePet/parent`. + public var parent: Components.Schemas.RecursivePet? { + get { + storage.value.parent + } + _modify { + yield &storage.value.parent + } + } + /// Creates a new `RecursivePet`. + /// + /// - Parameters: + /// - name: + /// - parent: + public init( + name: Swift.String, + parent: Components.Schemas.RecursivePet? = nil + ) { + storage = .init(value: .init( + name: name, + parent: parent + )) + } + public enum CodingKeys: String, CodingKey { + case name + case parent + } + public init(from decoder: any Decoder) throws { + storage = try .init(from: decoder) + } + public func encode(to encoder: any Encoder) throws { + try storage.encode(to: encoder) + } + /// Internal reference storage to allow type recursion. + private var storage: OpenAPIRuntime.CopyOnWriteBox + private struct Storage: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePet/name`. + var name: Swift.String + /// - Remark: Generated from `#/components/schemas/RecursivePet/parent`. + var parent: Components.Schemas.RecursivePet? + init( + name: Swift.String, + parent: Components.Schemas.RecursivePet? = nil + ) { + self.name = name + self.parent = parent + } + typealias CodingKeys = Components.Schemas.RecursivePet.CodingKeys + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetNested`. + public struct RecursivePetNested: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetNested/name`. + public var name: Swift.String { + get { + storage.value.name + } + _modify { + yield &storage.value.name + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetNested/parent`. + public struct parentPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetNested/parent/nested`. + public var nested: Components.Schemas.RecursivePetNested + /// Creates a new `parentPayload`. + /// + /// - Parameters: + /// - nested: + public init(nested: Components.Schemas.RecursivePetNested) { + self.nested = nested + } + public enum CodingKeys: String, CodingKey { + case nested + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetNested/parent`. + public var parent: Components.Schemas.RecursivePetNested.parentPayload? { + get { + storage.value.parent + } + _modify { + yield &storage.value.parent + } + } + /// Creates a new `RecursivePetNested`. + /// + /// - Parameters: + /// - name: + /// - parent: + public init( + name: Swift.String, + parent: Components.Schemas.RecursivePetNested.parentPayload? = nil + ) { + storage = .init(value: .init( + name: name, + parent: parent + )) + } + public enum CodingKeys: String, CodingKey { + case name + case parent + } + public init(from decoder: any Decoder) throws { + storage = try .init(from: decoder) + } + public func encode(to encoder: any Encoder) throws { + try storage.encode(to: encoder) + } + /// Internal reference storage to allow type recursion. + private var storage: OpenAPIRuntime.CopyOnWriteBox + private struct Storage: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetNested/name`. + var name: Swift.String + /// - Remark: Generated from `#/components/schemas/RecursivePetNested/parent`. + struct parentPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetNested/parent/nested`. + public var nested: Components.Schemas.RecursivePetNested + /// Creates a new `parentPayload`. + /// + /// - Parameters: + /// - nested: + public init(nested: Components.Schemas.RecursivePetNested) { + self.nested = nested + } + public enum CodingKeys: String, CodingKey { + case nested + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetNested/parent`. + var parent: Components.Schemas.RecursivePetNested.parentPayload? + init( + name: Swift.String, + parent: Components.Schemas.RecursivePetNested.parentPayload? = nil + ) { + self.name = name + self.parent = parent + } + typealias CodingKeys = Components.Schemas.RecursivePetNested.CodingKeys + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst`. + public struct RecursivePetOneOfFirst: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value1`. + public var value1: Components.Schemas.RecursivePetOneOf { + get { + storage.value.value1 + } + _modify { + yield &storage.value.value1 + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value2`. + public struct Value2Payload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value2/type`. + public var _type: Swift.String + /// Creates a new `Value2Payload`. + /// + /// - Parameters: + /// - _type: + public init(_type: Swift.String) { + self._type = _type + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value2`. + public var value2: Components.Schemas.RecursivePetOneOfFirst.Value2Payload { + get { + storage.value.value2 + } + _modify { + yield &storage.value.value2 + } + } + /// Creates a new `RecursivePetOneOfFirst`. + /// + /// - Parameters: + /// - value1: + /// - value2: + public init( + value1: Components.Schemas.RecursivePetOneOf, + value2: Components.Schemas.RecursivePetOneOfFirst.Value2Payload + ) { + storage = .init(value: .init( + value1: value1, + value2: value2 + )) + } + public init(from decoder: any Decoder) throws { + storage = try .init(from: decoder) + } + public func encode(to encoder: any Encoder) throws { + try storage.encode(to: encoder) + } + /// Internal reference storage to allow type recursion. + private var storage: OpenAPIRuntime.CopyOnWriteBox + private struct Storage: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value1`. + var value1: Components.Schemas.RecursivePetOneOf + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value2`. + struct Value2Payload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value2/type`. + public var _type: Swift.String + /// Creates a new `Value2Payload`. + /// + /// - Parameters: + /// - _type: + public init(_type: Swift.String) { + self._type = _type + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value2`. + var value2: Components.Schemas.RecursivePetOneOfFirst.Value2Payload + init( + value1: Components.Schemas.RecursivePetOneOf, + value2: Components.Schemas.RecursivePetOneOfFirst.Value2Payload + ) { + self.value1 = value1 + self.value2 = value2 + } + init(from decoder: any Decoder) throws { + value1 = try .init(from: decoder) + value2 = try .init(from: decoder) + } + func encode(to encoder: any Encoder) throws { + try value1.encode(to: encoder) + try value2.encode(to: encoder) + } + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfSecond`. + public struct RecursivePetOneOfSecond: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfSecond/value1`. + public var value1: Components.Schemas.Pet + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfSecond/value2`. + public struct Value2Payload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfSecond/value2/type`. + public var _type: Swift.String + /// Creates a new `Value2Payload`. + /// + /// - Parameters: + /// - _type: + public init(_type: Swift.String) { + self._type = _type + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfSecond/value2`. + public var value2: Components.Schemas.RecursivePetOneOfSecond.Value2Payload + /// Creates a new `RecursivePetOneOfSecond`. + /// + /// - Parameters: + /// - value1: + /// - value2: + public init( + value1: Components.Schemas.Pet, + value2: Components.Schemas.RecursivePetOneOfSecond.Value2Payload + ) { + self.value1 = value1 + self.value2 = value2 + } + public init(from decoder: any Decoder) throws { + value1 = try .init(from: decoder) + value2 = try .init(from: decoder) + } + public func encode(to encoder: any Encoder) throws { + try value1.encode(to: encoder) + try value2.encode(to: encoder) + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOf`. + @frozen public enum RecursivePetOneOf: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOf/RecursivePetOneOfFirst`. + case RecursivePetOneOfFirst(Components.Schemas.RecursivePetOneOfFirst) + /// - Remark: Generated from `#/components/schemas/RecursivePetOneOf/RecursivePetOneOfSecond`. + case RecursivePetOneOfSecond(Components.Schemas.RecursivePetOneOfSecond) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "RecursivePetOneOfFirst", "#/components/schemas/RecursivePetOneOfFirst": + self = .RecursivePetOneOfFirst(try .init(from: decoder)) + case "RecursivePetOneOfSecond", "#/components/schemas/RecursivePetOneOfSecond": + self = .RecursivePetOneOfSecond(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Encoder) throws { + switch self { + case let .RecursivePetOneOfFirst(value): + try value.encode(to: encoder) + case let .RecursivePetOneOfSecond(value): + try value.encode(to: encoder) + } + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetAnyOf`. + public struct RecursivePetAnyOf: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetAnyOf/value1`. + public var value1: Components.Schemas.RecursivePetAnyOf? { + get { + storage.value.value1 + } + _modify { + yield &storage.value.value1 + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetAnyOf/value2`. + public var value2: Swift.String? { + get { + storage.value.value2 + } + _modify { + yield &storage.value.value2 + } + } + /// Creates a new `RecursivePetAnyOf`. + /// + /// - Parameters: + /// - value1: + /// - value2: + public init( + value1: Components.Schemas.RecursivePetAnyOf? = nil, + value2: Swift.String? = nil + ) { + storage = .init(value: .init( + value1: value1, + value2: value2 + )) + } + public init(from decoder: any Decoder) throws { + storage = try .init(from: decoder) + } + public func encode(to encoder: any Encoder) throws { + try storage.encode(to: encoder) + } + /// Internal reference storage to allow type recursion. + private var storage: OpenAPIRuntime.CopyOnWriteBox + private struct Storage: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetAnyOf/value1`. + var value1: Components.Schemas.RecursivePetAnyOf? + /// - Remark: Generated from `#/components/schemas/RecursivePetAnyOf/value2`. + var value2: Swift.String? + init( + value1: Components.Schemas.RecursivePetAnyOf? = nil, + value2: Swift.String? = nil + ) { + self.value1 = value1 + self.value2 = value2 + } + init(from decoder: any Decoder) throws { + var errors: [any Error] = [] + do { + value1 = try .init(from: decoder) + } catch { + errors.append(error) + } + do { + value2 = try decoder.decodeFromSingleValueContainer() + } catch { + errors.append(error) + } + try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( + [ + value1, + value2 + ], + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) + } + func encode(to encoder: any Encoder) throws { + try encoder.encodeFirstNonNilValueToSingleValueContainer([ + value2 + ]) + try value1?.encode(to: encoder) + } + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetAllOf`. + public struct RecursivePetAllOf: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetAllOf/value1`. + public struct Value1Payload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetAllOf/value1/parent`. + public var parent: Components.Schemas.RecursivePetAllOf? + /// Creates a new `Value1Payload`. + /// + /// - Parameters: + /// - parent: + public init(parent: Components.Schemas.RecursivePetAllOf? = nil) { + self.parent = parent + } + public enum CodingKeys: String, CodingKey { + case parent + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetAllOf/value1`. + public var value1: Components.Schemas.RecursivePetAllOf.Value1Payload { + get { + storage.value.value1 + } + _modify { + yield &storage.value.value1 + } + } + /// Creates a new `RecursivePetAllOf`. + /// + /// - Parameters: + /// - value1: + public init(value1: Components.Schemas.RecursivePetAllOf.Value1Payload) { + storage = .init(value: .init(value1: value1)) + } + public init(from decoder: any Decoder) throws { + storage = try .init(from: decoder) + } + public func encode(to encoder: any Encoder) throws { + try storage.encode(to: encoder) + } + /// Internal reference storage to allow type recursion. + private var storage: OpenAPIRuntime.CopyOnWriteBox + private struct Storage: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetAllOf/value1`. + struct Value1Payload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/RecursivePetAllOf/value1/parent`. + public var parent: Components.Schemas.RecursivePetAllOf? + /// Creates a new `Value1Payload`. + /// + /// - Parameters: + /// - parent: + public init(parent: Components.Schemas.RecursivePetAllOf? = nil) { + self.parent = parent + } + public enum CodingKeys: String, CodingKey { + case parent + } + } + /// - Remark: Generated from `#/components/schemas/RecursivePetAllOf/value1`. + var value1: Components.Schemas.RecursivePetAllOf.Value1Payload + init(value1: Components.Schemas.RecursivePetAllOf.Value1Payload) { + self.value1 = value1 + } + init(from decoder: any Decoder) throws { + value1 = try .init(from: decoder) + } + func encode(to encoder: any Encoder) throws { + try value1.encode(to: encoder) + } + } + } + } + /// Types generated from the `#/components/parameters` section of the OpenAPI document. + public enum Parameters { + /// Supply this parameter to filter pets born since the provided date. + /// + /// - Remark: Generated from `#/components/parameters/query.born-since`. + public typealias query_period_born_hyphen_since = Components.Schemas.DOB + /// The id of the pet to retrieve + /// + /// - Remark: Generated from `#/components/parameters/path.petId`. + public typealias path_period_petId = Swift.Int64 + } + /// Types generated from the `#/components/requestBodies` section of the OpenAPI document. + public enum RequestBodies { + /// - Remark: Generated from `#/components/requestBodies/UpdatePetRequest`. + @frozen public enum UpdatePetRequest: Sendable, Hashable { + /// - Remark: Generated from `#/components/requestBodies/UpdatePetRequest/json`. + public struct jsonPayload: Codable, Hashable, Sendable { + /// Pet name + /// + /// - Remark: Generated from `#/components/requestBodies/UpdatePetRequest/json/name`. + public var name: Swift.String? + /// - Remark: Generated from `#/components/requestBodies/UpdatePetRequest/json/kind`. + public var kind: Components.Schemas.PetKind? + /// - Remark: Generated from `#/components/requestBodies/UpdatePetRequest/json/tag`. + public var tag: Swift.String? + /// Creates a new `jsonPayload`. + /// + /// - Parameters: + /// - name: Pet name + /// - kind: + /// - tag: + public init( + name: Swift.String? = nil, + kind: Components.Schemas.PetKind? = nil, + tag: Swift.String? = nil + ) { + self.name = name + self.kind = kind + self.tag = tag + } + public enum CodingKeys: String, CodingKey { + case name + case kind + case tag + } + } + /// - Remark: Generated from `#/components/requestBodies/UpdatePetRequest/content/application\/json`. + case json(Components.RequestBodies.UpdatePetRequest.jsonPayload) + } + /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest`. + @frozen public enum MultipartUploadTypedRequest: Sendable, Hashable { + /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm`. + @frozen public enum multipartFormPayload: Sendable, Hashable { + /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/log`. + public struct logPayload: Sendable, Hashable { + /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/log/headers`. + public struct Headers: Sendable, Hashable { + /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/log/headers/x-log-type`. + @frozen public enum x_hyphen_log_hyphen_typePayload: String, Codable, Hashable, Sendable, CaseIterable { + case structured = "structured" + case unstructured = "unstructured" + } + /// The type of the log. + /// + /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/log/headers/x-log-type`. + public var x_hyphen_log_hyphen_type: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.logPayload.Headers.x_hyphen_log_hyphen_typePayload? + /// Creates a new `Headers`. + /// + /// - Parameters: + /// - x_hyphen_log_hyphen_type: The type of the log. + public init(x_hyphen_log_hyphen_type: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.logPayload.Headers.x_hyphen_log_hyphen_typePayload? = nil) { + self.x_hyphen_log_hyphen_type = x_hyphen_log_hyphen_type + } + } + /// Received HTTP response headers + public var headers: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.logPayload.Headers + public var body: OpenAPIRuntime.HTTPBody + /// Creates a new `logPayload`. + /// + /// - Parameters: + /// - headers: Received HTTP response headers + /// - body: + public init( + headers: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.logPayload.Headers = .init(), + body: OpenAPIRuntime.HTTPBody + ) { + self.headers = headers + self.body = body + } + } + case log(OpenAPIRuntime.MultipartPart) + /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/metadata`. + public struct metadataPayload: Sendable, Hashable { + /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/metadata/content/body`. + public struct bodyPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/metadata/content/body/createdAt`. + public var createdAt: Foundation.Date + /// Creates a new `bodyPayload`. + /// + /// - Parameters: + /// - createdAt: + public init(createdAt: Foundation.Date) { + self.createdAt = createdAt + } + public enum CodingKeys: String, CodingKey { + case createdAt + } + } + public var body: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.metadataPayload.bodyPayload + /// Creates a new `metadataPayload`. + /// + /// - Parameters: + /// - body: + public init(body: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.metadataPayload.bodyPayload) { + self.body = body + } + } + case metadata(OpenAPIRuntime.MultipartPart) + /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/keyword`. + public struct keywordPayload: Sendable, Hashable { + public var body: OpenAPIRuntime.HTTPBody + /// Creates a new `keywordPayload`. + /// + /// - Parameters: + /// - body: + public init(body: OpenAPIRuntime.HTTPBody) { + self.body = body + } + } + case keyword(OpenAPIRuntime.MultipartPart) + case undocumented(OpenAPIRuntime.MultipartRawPart) + } + /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/content/multipart\/form-data`. + case multipartForm(OpenAPIRuntime.MultipartBody) + } + } + /// Types generated from the `#/components/responses` section of the OpenAPI document. + public enum Responses { + public struct ErrorBadRequest: Sendable, Hashable { + /// - Remark: Generated from `#/components/responses/ErrorBadRequest/headers`. + public struct Headers: Sendable, Hashable { + /// A description here. + /// + /// - Remark: Generated from `#/components/responses/ErrorBadRequest/headers/X-Reason`. + public var X_hyphen_Reason: Swift.String? + /// Creates a new `Headers`. + /// + /// - Parameters: + /// - X_hyphen_Reason: A description here. + public init(X_hyphen_Reason: Swift.String? = nil) { + self.X_hyphen_Reason = X_hyphen_Reason + } + } + /// Received HTTP response headers + public var headers: Components.Responses.ErrorBadRequest.Headers + /// - Remark: Generated from `#/components/responses/ErrorBadRequest/content`. + @frozen public enum Body: Sendable, Hashable { + /// - Remark: Generated from `#/components/responses/ErrorBadRequest/content/json`. + public struct jsonPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/responses/ErrorBadRequest/content/json/code`. + public var code: Swift.Int + /// Creates a new `jsonPayload`. + /// + /// - Parameters: + /// - code: + public init(code: Swift.Int) { + self.code = code + } + public enum CodingKeys: String, CodingKey { + case code + } + } + /// - Remark: Generated from `#/components/responses/ErrorBadRequest/content/application\/json`. + case json(Components.Responses.ErrorBadRequest.Body.jsonPayload) + /// The associated value of the enum case if `self` is `.json`. + /// + /// - Throws: An error if `self` is not `.json`. + /// - SeeAlso: `.json`. + public var json: Components.Responses.ErrorBadRequest.Body.jsonPayload { + get throws { + switch self { + case let .json(body): + return body + } + } + } + } + /// Received HTTP response body + public var body: Components.Responses.ErrorBadRequest.Body + /// Creates a new `ErrorBadRequest`. + /// + /// - Parameters: + /// - headers: Received HTTP response headers + /// - body: Received HTTP response body + public init( + headers: Components.Responses.ErrorBadRequest.Headers = .init(), + body: Components.Responses.ErrorBadRequest.Body + ) { + self.headers = headers + self.body = body + } + } + public struct MultipartDownloadTypedResponse: Sendable, Hashable { + /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content`. + @frozen public enum Body: Sendable, Hashable { + /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm`. + @frozen public enum multipartFormPayload: Sendable, Hashable { + /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/log`. + public struct logPayload: Sendable, Hashable { + /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/log/headers`. + public struct Headers: Sendable, Hashable { + /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/log/headers/x-log-type`. + @frozen public enum x_hyphen_log_hyphen_typePayload: String, Codable, Hashable, Sendable, CaseIterable { + case structured = "structured" + case unstructured = "unstructured" + } + /// The type of the log. + /// + /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/log/headers/x-log-type`. + public var x_hyphen_log_hyphen_type: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.logPayload.Headers.x_hyphen_log_hyphen_typePayload? + /// Creates a new `Headers`. + /// + /// - Parameters: + /// - x_hyphen_log_hyphen_type: The type of the log. + public init(x_hyphen_log_hyphen_type: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.logPayload.Headers.x_hyphen_log_hyphen_typePayload? = nil) { + self.x_hyphen_log_hyphen_type = x_hyphen_log_hyphen_type + } + } + /// Received HTTP response headers + public var headers: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.logPayload.Headers + public var body: OpenAPIRuntime.HTTPBody + /// Creates a new `logPayload`. + /// + /// - Parameters: + /// - headers: Received HTTP response headers + /// - body: + public init( + headers: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.logPayload.Headers = .init(), + body: OpenAPIRuntime.HTTPBody + ) { + self.headers = headers + self.body = body + } + } + case log(OpenAPIRuntime.MultipartPart) + /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/metadata`. + public struct metadataPayload: Sendable, Hashable { + /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/metadata/content/body`. + public struct bodyPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/metadata/content/body/createdAt`. + public var createdAt: Foundation.Date + /// Creates a new `bodyPayload`. + /// + /// - Parameters: + /// - createdAt: + public init(createdAt: Foundation.Date) { + self.createdAt = createdAt + } + public enum CodingKeys: String, CodingKey { + case createdAt + } + } + public var body: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.metadataPayload.bodyPayload + /// Creates a new `metadataPayload`. + /// + /// - Parameters: + /// - body: + public init(body: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.metadataPayload.bodyPayload) { + self.body = body + } + } + case metadata(OpenAPIRuntime.MultipartPart) + /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/keyword`. + public struct keywordPayload: Sendable, Hashable { + public var body: OpenAPIRuntime.HTTPBody + /// Creates a new `keywordPayload`. + /// + /// - Parameters: + /// - body: + public init(body: OpenAPIRuntime.HTTPBody) { + self.body = body + } + } + case keyword(OpenAPIRuntime.MultipartPart) + case undocumented(OpenAPIRuntime.MultipartRawPart) + } + /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipart\/form-data`. + case multipartForm(OpenAPIRuntime.MultipartBody) + /// The associated value of the enum case if `self` is `.multipartForm`. + /// + /// - Throws: An error if `self` is not `.multipartForm`. + /// - SeeAlso: `.multipartForm`. + public var multipartForm: OpenAPIRuntime.MultipartBody { + get throws { + switch self { + case let .multipartForm(body): + return body + } + } + } + } + /// Received HTTP response body + public var body: Components.Responses.MultipartDownloadTypedResponse.Body + /// Creates a new `MultipartDownloadTypedResponse`. + /// + /// - Parameters: + /// - body: Received HTTP response body + public init(body: Components.Responses.MultipartDownloadTypedResponse.Body) { + self.body = body + } + } + } + /// Types generated from the `#/components/headers` section of the OpenAPI document. + public enum Headers { + /// A description here. + /// + /// - Remark: Generated from `#/components/headers/TracingHeader`. + public typealias TracingHeader = Swift.String + } +} + +/// API operations, with input and output types, generated from `#/paths` in the OpenAPI document. +public enum Operations { + /// List all pets + /// + /// You can fetch + /// all the pets here + /// + /// - Remark: HTTP `GET /pets`. + /// - Remark: Generated from `#/paths//pets/get(listPets)`. + public enum listPets { + public static let id: Swift.String = "listPets" + public struct Input: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/GET/query`. + public struct Query: Sendable, Hashable { + /// How many items to return at one time (max 100) + /// + /// - Remark: Generated from `#/paths/pets/GET/query/limit`. + public var limit: Swift.Int32? + /// - Remark: Generated from `#/paths/pets/GET/query/habitat`. + @frozen public enum habitatPayload: String, Codable, Hashable, Sendable, CaseIterable { + case water = "water" + case land = "land" + case air = "air" + case _empty = "" + } + /// - Remark: Generated from `#/paths/pets/GET/query/habitat`. + public var habitat: Operations.listPets.Input.Query.habitatPayload? + /// - Remark: Generated from `#/paths/pets/GET/query/feedsPayload`. + @frozen public enum feedsPayloadPayload: String, Codable, Hashable, Sendable, CaseIterable { + case omnivore = "omnivore" + case carnivore = "carnivore" + case herbivore = "herbivore" + } + /// - Remark: Generated from `#/paths/pets/GET/query/feeds`. + public typealias feedsPayload = [Operations.listPets.Input.Query.feedsPayloadPayload] + /// - Remark: Generated from `#/paths/pets/GET/query/feeds`. + public var feeds: Operations.listPets.Input.Query.feedsPayload? + /// Supply this parameter to filter pets born since the provided date. + /// + /// - Remark: Generated from `#/paths/pets/GET/query/since`. + public var since: Components.Parameters.query_period_born_hyphen_since? + /// Creates a new `Query`. + /// + /// - Parameters: + /// - limit: How many items to return at one time (max 100) + /// - habitat: + /// - feeds: + /// - since: Supply this parameter to filter pets born since the provided date. + public init( + limit: Swift.Int32? = nil, + habitat: Operations.listPets.Input.Query.habitatPayload? = nil, + feeds: Operations.listPets.Input.Query.feedsPayload? = nil, + since: Components.Parameters.query_period_born_hyphen_since? = nil + ) { + self.limit = limit + self.habitat = habitat + self.feeds = feeds + self.since = since + } + } + public var query: Operations.listPets.Input.Query + /// - Remark: Generated from `#/paths/pets/GET/header`. + public struct Headers: Sendable, Hashable { + /// Request identifier + /// + /// - Remark: Generated from `#/paths/pets/GET/header/My-Request-UUID`. + public var My_hyphen_Request_hyphen_UUID: Swift.String? + public var accept: [OpenAPIRuntime.AcceptHeaderContentType] + /// Creates a new `Headers`. + /// + /// - Parameters: + /// - My_hyphen_Request_hyphen_UUID: Request identifier + /// - accept: + public init( + My_hyphen_Request_hyphen_UUID: Swift.String? = nil, + accept: [OpenAPIRuntime.AcceptHeaderContentType] = .defaultValues() + ) { + self.My_hyphen_Request_hyphen_UUID = My_hyphen_Request_hyphen_UUID + self.accept = accept + } + } + public var headers: Operations.listPets.Input.Headers + /// Creates a new `Input`. + /// + /// - Parameters: + /// - query: + /// - headers: + public init( + query: Operations.listPets.Input.Query = .init(), + headers: Operations.listPets.Input.Headers = .init() + ) { + self.query = query + self.headers = headers + } + } + @frozen public enum Output: Sendable, Hashable { + public struct Ok: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/GET/responses/200/headers`. + public struct Headers: Sendable, Hashable { + /// Response identifier + /// + /// - Remark: Generated from `#/paths/pets/GET/responses/200/headers/My-Response-UUID`. + public var My_hyphen_Response_hyphen_UUID: Swift.String + /// A description here. + /// + /// - Remark: Generated from `#/paths/pets/GET/responses/200/headers/My-Tracing-Header`. + public var My_hyphen_Tracing_hyphen_Header: Components.Headers.TracingHeader? + /// Creates a new `Headers`. + /// + /// - Parameters: + /// - My_hyphen_Response_hyphen_UUID: Response identifier + /// - My_hyphen_Tracing_hyphen_Header: A description here. + public init( + My_hyphen_Response_hyphen_UUID: Swift.String, + My_hyphen_Tracing_hyphen_Header: Components.Headers.TracingHeader? = nil + ) { + self.My_hyphen_Response_hyphen_UUID = My_hyphen_Response_hyphen_UUID + self.My_hyphen_Tracing_hyphen_Header = My_hyphen_Tracing_hyphen_Header + } + } + /// Received HTTP response headers + public var headers: Operations.listPets.Output.Ok.Headers + /// - Remark: Generated from `#/paths/pets/GET/responses/200/content`. + @frozen public enum Body: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/GET/responses/200/content/application\/json`. + case json(Components.Schemas.Pets) + /// The associated value of the enum case if `self` is `.json`. + /// + /// - Throws: An error if `self` is not `.json`. + /// - SeeAlso: `.json`. + public var json: Components.Schemas.Pets { + get throws { + switch self { + case let .json(body): + return body + } + } + } + } + /// Received HTTP response body + public var body: Operations.listPets.Output.Ok.Body + /// Creates a new `Ok`. + /// + /// - Parameters: + /// - headers: Received HTTP response headers + /// - body: Received HTTP response body + public init( + headers: Operations.listPets.Output.Ok.Headers, + body: Operations.listPets.Output.Ok.Body + ) { + self.headers = headers + self.body = body + } + } + /// A paged array of pets + /// + /// - Remark: Generated from `#/paths//pets/get(listPets)/responses/200`. + /// + /// HTTP response code: `200 ok`. + case ok(Operations.listPets.Output.Ok) + /// The associated value of the enum case if `self` is `.ok`. + /// + /// - Throws: An error if `self` is not `.ok`. + /// - SeeAlso: `.ok`. + public var ok: Operations.listPets.Output.Ok { + get throws { + switch self { + case let .ok(response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "ok", + response: self + ) + } + } + } + public struct Default: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/GET/responses/default/content`. + @frozen public enum Body: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/GET/responses/default/content/application\/json`. + case json(Components.Schemas._Error) + /// The associated value of the enum case if `self` is `.json`. + /// + /// - Throws: An error if `self` is not `.json`. + /// - SeeAlso: `.json`. + public var json: Components.Schemas._Error { + get throws { + switch self { + case let .json(body): + return body + } + } + } + } + /// Received HTTP response body + public var body: Operations.listPets.Output.Default.Body + /// Creates a new `Default`. + /// + /// - Parameters: + /// - body: Received HTTP response body + public init(body: Operations.listPets.Output.Default.Body) { + self.body = body + } + } + /// Unexpected error + /// + /// - Remark: Generated from `#/paths//pets/get(listPets)/responses/default`. + /// + /// HTTP response code: `default`. + case `default`(statusCode: Swift.Int, Operations.listPets.Output.Default) + /// The associated value of the enum case if `self` is `.`default``. + /// + /// - Throws: An error if `self` is not `.`default``. + /// - SeeAlso: `.`default``. + public var `default`: Operations.listPets.Output.Default { + get throws { + switch self { + case let .`default`(_, response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "default", + response: self + ) + } + } + } + } + @frozen public enum AcceptableContentType: AcceptableProtocol { + case json + case other(Swift.String) + public init?(rawValue: Swift.String) { + switch rawValue.lowercased() { + case "application/json": + self = .json + default: + self = .other(rawValue) + } + } + public var rawValue: Swift.String { + switch self { + case let .other(string): + return string + case .json: + return "application/json" + } + } + public static var allCases: [Self] { + [ + .json + ] + } + } + } + /// Create a pet + /// + /// - Remark: HTTP `POST /pets`. + /// - Remark: Generated from `#/paths//pets/post(createPet)`. + public enum createPet { + public static let id: Swift.String = "createPet" + public struct Input: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/POST/header`. + public struct Headers: Sendable, Hashable { + /// A description here. + /// + /// - Remark: Generated from `#/paths/pets/POST/header/X-Extra-Arguments`. + public var X_hyphen_Extra_hyphen_Arguments: Components.Schemas.CodeError? + public var accept: [OpenAPIRuntime.AcceptHeaderContentType] + /// Creates a new `Headers`. + /// + /// - Parameters: + /// - X_hyphen_Extra_hyphen_Arguments: A description here. + /// - accept: + public init( + X_hyphen_Extra_hyphen_Arguments: Components.Schemas.CodeError? = nil, + accept: [OpenAPIRuntime.AcceptHeaderContentType] = .defaultValues() + ) { + self.X_hyphen_Extra_hyphen_Arguments = X_hyphen_Extra_hyphen_Arguments + self.accept = accept + } + } + public var headers: Operations.createPet.Input.Headers + /// - Remark: Generated from `#/paths/pets/POST/requestBody`. + @frozen public enum Body: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/POST/requestBody/content/application\/json`. + case json(Components.Schemas.CreatePetRequest) + } + public var body: Operations.createPet.Input.Body + /// Creates a new `Input`. + /// + /// - Parameters: + /// - headers: + /// - body: + public init( + headers: Operations.createPet.Input.Headers = .init(), + body: Operations.createPet.Input.Body + ) { + self.headers = headers + self.body = body + } + } + @frozen public enum Output: Sendable, Hashable { + public struct Created: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/POST/responses/201/headers`. + public struct Headers: Sendable, Hashable { + /// A description here. + /// + /// - Remark: Generated from `#/paths/pets/POST/responses/201/headers/X-Extra-Arguments`. + public var X_hyphen_Extra_hyphen_Arguments: Components.Schemas.CodeError? + /// Creates a new `Headers`. + /// + /// - Parameters: + /// - X_hyphen_Extra_hyphen_Arguments: A description here. + public init(X_hyphen_Extra_hyphen_Arguments: Components.Schemas.CodeError? = nil) { + self.X_hyphen_Extra_hyphen_Arguments = X_hyphen_Extra_hyphen_Arguments + } + } + /// Received HTTP response headers + public var headers: Operations.createPet.Output.Created.Headers + /// - Remark: Generated from `#/paths/pets/POST/responses/201/content`. + @frozen public enum Body: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/POST/responses/201/content/application\/json`. + case json(Components.Schemas.Pet) + /// The associated value of the enum case if `self` is `.json`. + /// + /// - Throws: An error if `self` is not `.json`. + /// - SeeAlso: `.json`. + public var json: Components.Schemas.Pet { + get throws { + switch self { + case let .json(body): + return body + } + } + } + } + /// Received HTTP response body + public var body: Operations.createPet.Output.Created.Body + /// Creates a new `Created`. + /// + /// - Parameters: + /// - headers: Received HTTP response headers + /// - body: Received HTTP response body + public init( + headers: Operations.createPet.Output.Created.Headers = .init(), + body: Operations.createPet.Output.Created.Body + ) { + self.headers = headers + self.body = body + } + } + /// Successfully created pet + /// + /// - Remark: Generated from `#/paths//pets/post(createPet)/responses/201`. + /// + /// HTTP response code: `201 created`. + case created(Operations.createPet.Output.Created) + /// The associated value of the enum case if `self` is `.created`. + /// + /// - Throws: An error if `self` is not `.created`. + /// - SeeAlso: `.created`. + public var created: Operations.createPet.Output.Created { + get throws { + switch self { + case let .created(response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "created", + response: self + ) + } + } + } + /// Bad request + /// + /// - Remark: Generated from `#/paths//pets/post(createPet)/responses/4XX`. + /// + /// HTTP response code: `400...499 clientError`. + case clientError(statusCode: Swift.Int, Components.Responses.ErrorBadRequest) + /// The associated value of the enum case if `self` is `.clientError`. + /// + /// - Throws: An error if `self` is not `.clientError`. + /// - SeeAlso: `.clientError`. + public var clientError: Components.Responses.ErrorBadRequest { + get throws { + switch self { + case let .clientError(_, response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "clientError", + response: self + ) + } + } + } + /// Undocumented response. + /// + /// A response with a code that is not documented in the OpenAPI document. + case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) + } + @frozen public enum AcceptableContentType: AcceptableProtocol { + case json + case other(Swift.String) + public init?(rawValue: Swift.String) { + switch rawValue.lowercased() { + case "application/json": + self = .json + default: + self = .other(rawValue) + } + } + public var rawValue: Swift.String { + switch self { + case let .other(string): + return string + case .json: + return "application/json" + } + } + public static var allCases: [Self] { + [ + .json + ] + } + } + } + /// Create a pet using a url form + /// + /// - Remark: HTTP `POST /pets/create`. + /// - Remark: Generated from `#/paths//pets/create/post(createPetWithForm)`. + public enum createPetWithForm { + public static let id: Swift.String = "createPetWithForm" + public struct Input: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/create/POST/requestBody`. + @frozen public enum Body: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/create/POST/requestBody/content/application\/x-www-form-urlencoded`. + case urlEncodedForm(Components.Schemas.CreatePetRequest) + } + public var body: Operations.createPetWithForm.Input.Body + /// Creates a new `Input`. + /// + /// - Parameters: + /// - body: + public init(body: Operations.createPetWithForm.Input.Body) { + self.body = body + } + } + @frozen public enum Output: Sendable, Hashable { + public struct NoContent: Sendable, Hashable { + /// Creates a new `NoContent`. + public init() {} + } + /// Successfully created pet using a url form + /// + /// - Remark: Generated from `#/paths//pets/create/post(createPetWithForm)/responses/204`. + /// + /// HTTP response code: `204 noContent`. + case noContent(Operations.createPetWithForm.Output.NoContent) + /// The associated value of the enum case if `self` is `.noContent`. + /// + /// - Throws: An error if `self` is not `.noContent`. + /// - SeeAlso: `.noContent`. + public var noContent: Operations.createPetWithForm.Output.NoContent { + get throws { + switch self { + case let .noContent(response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "noContent", + response: self + ) + } + } + } + /// Undocumented response. + /// + /// A response with a code that is not documented in the OpenAPI document. + case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) + } + } + /// - Remark: HTTP `GET /pets/stats`. + /// - Remark: Generated from `#/paths//pets/stats/get(getStats)`. + public enum getStats { + public static let id: Swift.String = "getStats" + public struct Input: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/stats/GET/header`. + public struct Headers: Sendable, Hashable { + public var accept: [OpenAPIRuntime.AcceptHeaderContentType] + /// Creates a new `Headers`. + /// + /// - Parameters: + /// - accept: + public init(accept: [OpenAPIRuntime.AcceptHeaderContentType] = .defaultValues()) { + self.accept = accept + } + } + public var headers: Operations.getStats.Input.Headers + /// Creates a new `Input`. + /// + /// - Parameters: + /// - headers: + public init(headers: Operations.getStats.Input.Headers = .init()) { + self.headers = headers + } + } + @frozen public enum Output: Sendable, Hashable { + public struct Ok: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/stats/GET/responses/200/content`. + @frozen public enum Body: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/stats/GET/responses/200/content/application\/json`. + case json(Components.Schemas.PetStats) + /// The associated value of the enum case if `self` is `.json`. + /// + /// - Throws: An error if `self` is not `.json`. + /// - SeeAlso: `.json`. + public var json: Components.Schemas.PetStats { + get throws { + switch self { + case let .json(body): + return body + default: + try throwUnexpectedResponseBody( + expectedContent: "application/json", + body: self + ) + } + } + } + /// - Remark: Generated from `#/paths/pets/stats/GET/responses/200/content/text\/plain`. + case plainText(OpenAPIRuntime.HTTPBody) + /// The associated value of the enum case if `self` is `.plainText`. + /// + /// - Throws: An error if `self` is not `.plainText`. + /// - SeeAlso: `.plainText`. + public var plainText: OpenAPIRuntime.HTTPBody { + get throws { + switch self { + case let .plainText(body): + return body + default: + try throwUnexpectedResponseBody( + expectedContent: "text/plain", + body: self + ) + } + } + } + /// - Remark: Generated from `#/paths/pets/stats/GET/responses/200/content/application\/octet-stream`. + case binary(OpenAPIRuntime.HTTPBody) + /// The associated value of the enum case if `self` is `.binary`. + /// + /// - Throws: An error if `self` is not `.binary`. + /// - SeeAlso: `.binary`. + public var binary: OpenAPIRuntime.HTTPBody { + get throws { + switch self { + case let .binary(body): + return body + default: + try throwUnexpectedResponseBody( + expectedContent: "application/octet-stream", + body: self + ) + } + } + } + } + /// Received HTTP response body + public var body: Operations.getStats.Output.Ok.Body + /// Creates a new `Ok`. + /// + /// - Parameters: + /// - body: Received HTTP response body + public init(body: Operations.getStats.Output.Ok.Body) { + self.body = body + } + } + /// A successful response. + /// + /// - Remark: Generated from `#/paths//pets/stats/get(getStats)/responses/200`. + /// + /// HTTP response code: `200 ok`. + case ok(Operations.getStats.Output.Ok) + /// The associated value of the enum case if `self` is `.ok`. + /// + /// - Throws: An error if `self` is not `.ok`. + /// - SeeAlso: `.ok`. + public var ok: Operations.getStats.Output.Ok { + get throws { + switch self { + case let .ok(response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "ok", + response: self + ) + } + } + } + /// Undocumented response. + /// + /// A response with a code that is not documented in the OpenAPI document. + case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) + } + @frozen public enum AcceptableContentType: AcceptableProtocol { + case json + case plainText + case binary + case other(Swift.String) + public init?(rawValue: Swift.String) { + switch rawValue.lowercased() { + case "application/json": + self = .json + case "text/plain": + self = .plainText + case "application/octet-stream": + self = .binary + default: + self = .other(rawValue) + } + } + public var rawValue: Swift.String { + switch self { + case let .other(string): + return string + case .json: + return "application/json" + case .plainText: + return "text/plain" + case .binary: + return "application/octet-stream" + } + } + public static var allCases: [Self] { + [ + .json, + .plainText, + .binary + ] + } + } + } + /// - Remark: HTTP `POST /pets/stats`. + /// - Remark: Generated from `#/paths//pets/stats/post(postStats)`. + public enum postStats { + public static let id: Swift.String = "postStats" + public struct Input: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/stats/POST/requestBody`. + @frozen public enum Body: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/stats/POST/requestBody/content/application\/json`. + case json(Components.Schemas.PetStats) + /// - Remark: Generated from `#/paths/pets/stats/POST/requestBody/content/text\/plain`. + case plainText(OpenAPIRuntime.HTTPBody) + /// - Remark: Generated from `#/paths/pets/stats/POST/requestBody/content/application\/octet-stream`. + case binary(OpenAPIRuntime.HTTPBody) + } + public var body: Operations.postStats.Input.Body + /// Creates a new `Input`. + /// + /// - Parameters: + /// - body: + public init(body: Operations.postStats.Input.Body) { + self.body = body + } + } + @frozen public enum Output: Sendable, Hashable { + public struct Accepted: Sendable, Hashable { + /// Creates a new `Accepted`. + public init() {} + } + /// Accepted data. + /// + /// - Remark: Generated from `#/paths//pets/stats/post(postStats)/responses/202`. + /// + /// HTTP response code: `202 accepted`. + case accepted(Operations.postStats.Output.Accepted) + /// The associated value of the enum case if `self` is `.accepted`. + /// + /// - Throws: An error if `self` is not `.accepted`. + /// - SeeAlso: `.accepted`. + public var accepted: Operations.postStats.Output.Accepted { + get throws { + switch self { + case let .accepted(response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "accepted", + response: self + ) + } + } + } + /// Undocumented response. + /// + /// A response with a code that is not documented in the OpenAPI document. + case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) + } + } + /// - Remark: HTTP `POST /probe/`. + /// - Remark: Generated from `#/paths//probe//post(probe)`. + public enum probe { + public static let id: Swift.String = "probe" + public struct Input: Sendable, Hashable { + /// Creates a new `Input`. + public init() {} + } + @frozen public enum Output: Sendable, Hashable { + public struct NoContent: Sendable, Hashable { + /// Creates a new `NoContent`. + public init() {} + } + /// Ack + /// + /// - Remark: Generated from `#/paths//probe//post(probe)/responses/204`. + /// + /// HTTP response code: `204 noContent`. + case noContent(Operations.probe.Output.NoContent) + /// The associated value of the enum case if `self` is `.noContent`. + /// + /// - Throws: An error if `self` is not `.noContent`. + /// - SeeAlso: `.noContent`. + public var noContent: Operations.probe.Output.NoContent { + get throws { + switch self { + case let .noContent(response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "noContent", + response: self + ) + } + } + } + /// Undocumented response. + /// + /// A response with a code that is not documented in the OpenAPI document. + case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) + } + } + /// Update just a specific property of an existing pet. Nothing is updated if no request body is provided. + /// + /// - Remark: HTTP `PATCH /pets/{petId}`. + /// - Remark: Generated from `#/paths//pets/{petId}/patch(updatePet)`. + public enum updatePet { + public static let id: Swift.String = "updatePet" + public struct Input: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/{petId}/PATCH/path`. + public struct Path: Sendable, Hashable { + /// Id of the pet + /// + /// - Remark: Generated from `#/paths/pets/{petId}/PATCH/path/petId`. + public var petId: Swift.Int64 + /// Creates a new `Path`. + /// + /// - Parameters: + /// - petId: Id of the pet + public init(petId: Swift.Int64) { + self.petId = petId + } + } + public var path: Operations.updatePet.Input.Path + /// - Remark: Generated from `#/paths/pets/{petId}/PATCH/header`. + public struct Headers: Sendable, Hashable { + public var accept: [OpenAPIRuntime.AcceptHeaderContentType] + /// Creates a new `Headers`. + /// + /// - Parameters: + /// - accept: + public init(accept: [OpenAPIRuntime.AcceptHeaderContentType] = .defaultValues()) { + self.accept = accept + } + } + public var headers: Operations.updatePet.Input.Headers + public var body: Components.RequestBodies.UpdatePetRequest? + /// Creates a new `Input`. + /// + /// - Parameters: + /// - path: + /// - headers: + /// - body: + public init( + path: Operations.updatePet.Input.Path, + headers: Operations.updatePet.Input.Headers = .init(), + body: Components.RequestBodies.UpdatePetRequest? = nil + ) { + self.path = path + self.headers = headers + self.body = body + } + } + @frozen public enum Output: Sendable, Hashable { + public struct NoContent: Sendable, Hashable { + /// Creates a new `NoContent`. + public init() {} + } + /// Successfully updated + /// + /// - Remark: Generated from `#/paths//pets/{petId}/patch(updatePet)/responses/204`. + /// + /// HTTP response code: `204 noContent`. + case noContent(Operations.updatePet.Output.NoContent) + /// The associated value of the enum case if `self` is `.noContent`. + /// + /// - Throws: An error if `self` is not `.noContent`. + /// - SeeAlso: `.noContent`. + public var noContent: Operations.updatePet.Output.NoContent { + get throws { + switch self { + case let .noContent(response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "noContent", + response: self + ) + } + } + } + public struct BadRequest: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/{petId}/PATCH/responses/400/content`. + @frozen public enum Body: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/{petId}/PATCH/responses/400/content/json`. + public struct jsonPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/paths/pets/{petId}/PATCH/responses/400/content/json/message`. + public var message: Swift.String + /// Creates a new `jsonPayload`. + /// + /// - Parameters: + /// - message: + public init(message: Swift.String) { + self.message = message + } + public enum CodingKeys: String, CodingKey { + case message + } + } + /// - Remark: Generated from `#/paths/pets/{petId}/PATCH/responses/400/content/application\/json`. + case json(Operations.updatePet.Output.BadRequest.Body.jsonPayload) + /// The associated value of the enum case if `self` is `.json`. + /// + /// - Throws: An error if `self` is not `.json`. + /// - SeeAlso: `.json`. + public var json: Operations.updatePet.Output.BadRequest.Body.jsonPayload { + get throws { + switch self { + case let .json(body): + return body + } + } + } + } + /// Received HTTP response body + public var body: Operations.updatePet.Output.BadRequest.Body + /// Creates a new `BadRequest`. + /// + /// - Parameters: + /// - body: Received HTTP response body + public init(body: Operations.updatePet.Output.BadRequest.Body) { + self.body = body + } + } + /// Update input error + /// + /// - Remark: Generated from `#/paths//pets/{petId}/patch(updatePet)/responses/400`. + /// + /// HTTP response code: `400 badRequest`. + case badRequest(Operations.updatePet.Output.BadRequest) + /// The associated value of the enum case if `self` is `.badRequest`. + /// + /// - Throws: An error if `self` is not `.badRequest`. + /// - SeeAlso: `.badRequest`. + public var badRequest: Operations.updatePet.Output.BadRequest { + get throws { + switch self { + case let .badRequest(response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "badRequest", + response: self + ) + } + } + } + /// Undocumented response. + /// + /// A response with a code that is not documented in the OpenAPI document. + case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) + } + @frozen public enum AcceptableContentType: AcceptableProtocol { + case json + case other(Swift.String) + public init?(rawValue: Swift.String) { + switch rawValue.lowercased() { + case "application/json": + self = .json + default: + self = .other(rawValue) + } + } + public var rawValue: Swift.String { + switch self { + case let .other(string): + return string + case .json: + return "application/json" + } + } + public static var allCases: [Self] { + [ + .json + ] + } + } + } + /// Upload an avatar + /// + /// - Remark: HTTP `PUT /pets/{petId}/avatar`. + /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)`. + public enum uploadAvatarForPet { + public static let id: Swift.String = "uploadAvatarForPet" + public struct Input: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/path`. + public struct Path: Sendable, Hashable { + /// The id of the pet to retrieve + /// + /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/path/petId`. + public var petId: Components.Parameters.path_period_petId + /// Creates a new `Path`. + /// + /// - Parameters: + /// - petId: The id of the pet to retrieve + public init(petId: Components.Parameters.path_period_petId) { + self.petId = petId + } + } + public var path: Operations.uploadAvatarForPet.Input.Path + /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/header`. + public struct Headers: Sendable, Hashable { + public var accept: [OpenAPIRuntime.AcceptHeaderContentType] + /// Creates a new `Headers`. + /// + /// - Parameters: + /// - accept: + public init(accept: [OpenAPIRuntime.AcceptHeaderContentType] = .defaultValues()) { + self.accept = accept + } + } + public var headers: Operations.uploadAvatarForPet.Input.Headers + /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/requestBody`. + @frozen public enum Body: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/requestBody/content/application\/octet-stream`. + case binary(OpenAPIRuntime.HTTPBody) + } + public var body: Operations.uploadAvatarForPet.Input.Body + /// Creates a new `Input`. + /// + /// - Parameters: + /// - path: + /// - headers: + /// - body: + public init( + path: Operations.uploadAvatarForPet.Input.Path, + headers: Operations.uploadAvatarForPet.Input.Headers = .init(), + body: Operations.uploadAvatarForPet.Input.Body + ) { + self.path = path + self.headers = headers + self.body = body + } + } + @frozen public enum Output: Sendable, Hashable { + public struct Ok: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/responses/200/content`. + @frozen public enum Body: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/responses/200/content/application\/octet-stream`. + case binary(OpenAPIRuntime.HTTPBody) + /// The associated value of the enum case if `self` is `.binary`. + /// + /// - Throws: An error if `self` is not `.binary`. + /// - SeeAlso: `.binary`. + public var binary: OpenAPIRuntime.HTTPBody { + get throws { + switch self { + case let .binary(body): + return body + } + } + } + } + /// Received HTTP response body + public var body: Operations.uploadAvatarForPet.Output.Ok.Body + /// Creates a new `Ok`. + /// + /// - Parameters: + /// - body: Received HTTP response body + public init(body: Operations.uploadAvatarForPet.Output.Ok.Body) { + self.body = body + } + } + /// Echoes avatar back + /// + /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)/responses/200`. + /// + /// HTTP response code: `200 ok`. + case ok(Operations.uploadAvatarForPet.Output.Ok) + /// The associated value of the enum case if `self` is `.ok`. + /// + /// - Throws: An error if `self` is not `.ok`. + /// - SeeAlso: `.ok`. + public var ok: Operations.uploadAvatarForPet.Output.Ok { + get throws { + switch self { + case let .ok(response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "ok", + response: self + ) + } + } + } + public struct PreconditionFailed: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/responses/412/content`. + @frozen public enum Body: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/responses/412/content/application\/json`. + case json(Swift.String) + /// The associated value of the enum case if `self` is `.json`. + /// + /// - Throws: An error if `self` is not `.json`. + /// - SeeAlso: `.json`. + public var json: Swift.String { + get throws { + switch self { + case let .json(body): + return body + } + } + } + } + /// Received HTTP response body + public var body: Operations.uploadAvatarForPet.Output.PreconditionFailed.Body + /// Creates a new `PreconditionFailed`. + /// + /// - Parameters: + /// - body: Received HTTP response body + public init(body: Operations.uploadAvatarForPet.Output.PreconditionFailed.Body) { + self.body = body + } + } + /// Avatar is not acceptable + /// + /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)/responses/412`. + /// + /// HTTP response code: `412 preconditionFailed`. + case preconditionFailed(Operations.uploadAvatarForPet.Output.PreconditionFailed) + /// The associated value of the enum case if `self` is `.preconditionFailed`. + /// + /// - Throws: An error if `self` is not `.preconditionFailed`. + /// - SeeAlso: `.preconditionFailed`. + public var preconditionFailed: Operations.uploadAvatarForPet.Output.PreconditionFailed { + get throws { + switch self { + case let .preconditionFailed(response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "preconditionFailed", + response: self + ) + } + } + } + public struct InternalServerError: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/responses/500/content`. + @frozen public enum Body: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/responses/500/content/text\/plain`. + case plainText(OpenAPIRuntime.HTTPBody) + /// The associated value of the enum case if `self` is `.plainText`. + /// + /// - Throws: An error if `self` is not `.plainText`. + /// - SeeAlso: `.plainText`. + public var plainText: OpenAPIRuntime.HTTPBody { + get throws { + switch self { + case let .plainText(body): + return body + } + } + } + } + /// Received HTTP response body + public var body: Operations.uploadAvatarForPet.Output.InternalServerError.Body + /// Creates a new `InternalServerError`. + /// + /// - Parameters: + /// - body: Received HTTP response body + public init(body: Operations.uploadAvatarForPet.Output.InternalServerError.Body) { + self.body = body + } + } + /// Server error + /// + /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)/responses/500`. + /// + /// HTTP response code: `500 internalServerError`. + case internalServerError(Operations.uploadAvatarForPet.Output.InternalServerError) + /// The associated value of the enum case if `self` is `.internalServerError`. + /// + /// - Throws: An error if `self` is not `.internalServerError`. + /// - SeeAlso: `.internalServerError`. + public var internalServerError: Operations.uploadAvatarForPet.Output.InternalServerError { + get throws { + switch self { + case let .internalServerError(response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "internalServerError", + response: self + ) + } + } + } + /// Undocumented response. + /// + /// A response with a code that is not documented in the OpenAPI document. + case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) + } + @frozen public enum AcceptableContentType: AcceptableProtocol { + case binary + case json + case plainText + case other(Swift.String) + public init?(rawValue: Swift.String) { + switch rawValue.lowercased() { + case "application/octet-stream": + self = .binary + case "application/json": + self = .json + case "text/plain": + self = .plainText + default: + self = .other(rawValue) + } + } + public var rawValue: Swift.String { + switch self { + case let .other(string): + return string + case .binary: + return "application/octet-stream" + case .json: + return "application/json" + case .plainText: + return "text/plain" + } + } + public static var allCases: [Self] { + [ + .binary, + .json, + .plainText + ] + } + } + } + /// - Remark: HTTP `GET /pets/multipart-typed`. + /// - Remark: Generated from `#/paths//pets/multipart-typed/get(multipartDownloadTyped)`. + public enum multipartDownloadTyped { + public static let id: Swift.String = "multipartDownloadTyped" + public struct Input: Sendable, Hashable { + /// - Remark: Generated from `#/paths/pets/multipart-typed/GET/header`. + public struct Headers: Sendable, Hashable { + public var accept: [OpenAPIRuntime.AcceptHeaderContentType] + /// Creates a new `Headers`. + /// + /// - Parameters: + /// - accept: + public init(accept: [OpenAPIRuntime.AcceptHeaderContentType] = .defaultValues()) { + self.accept = accept + } + } + public var headers: Operations.multipartDownloadTyped.Input.Headers + /// Creates a new `Input`. + /// + /// - Parameters: + /// - headers: + public init(headers: Operations.multipartDownloadTyped.Input.Headers = .init()) { + self.headers = headers + } + } + @frozen public enum Output: Sendable, Hashable { + /// A typed multipart response. + /// + /// - Remark: Generated from `#/paths//pets/multipart-typed/get(multipartDownloadTyped)/responses/200`. + /// + /// HTTP response code: `200 ok`. + case ok(Components.Responses.MultipartDownloadTypedResponse) + /// The associated value of the enum case if `self` is `.ok`. + /// + /// - Throws: An error if `self` is not `.ok`. + /// - SeeAlso: `.ok`. + public var ok: Components.Responses.MultipartDownloadTypedResponse { + get throws { + switch self { + case let .ok(response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "ok", + response: self + ) + } + } + } + /// Undocumented response. + /// + /// A response with a code that is not documented in the OpenAPI document. + case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) + } + @frozen public enum AcceptableContentType: AcceptableProtocol { + case multipartForm + case other(Swift.String) + public init?(rawValue: Swift.String) { + switch rawValue.lowercased() { + case "multipart/form-data": + self = .multipartForm + default: + self = .other(rawValue) + } + } + public var rawValue: Swift.String { + switch self { + case let .other(string): + return string + case .multipartForm: + return "multipart/form-data" + } + } + public static var allCases: [Self] { + [ + .multipartForm + ] + } + } + } + /// - Remark: HTTP `POST /pets/multipart-typed`. + /// - Remark: Generated from `#/paths//pets/multipart-typed/post(multipartUploadTyped)`. + public enum multipartUploadTyped { + public static let id: Swift.String = "multipartUploadTyped" + public struct Input: Sendable, Hashable { + public var body: Components.RequestBodies.MultipartUploadTypedRequest + /// Creates a new `Input`. + /// + /// - Parameters: + /// - body: + public init(body: Components.RequestBodies.MultipartUploadTypedRequest) { + self.body = body + } + } + @frozen public enum Output: Sendable, Hashable { + public struct Accepted: Sendable, Hashable { + /// Creates a new `Accepted`. + public init() {} + } + /// Successfully accepted the data. + /// + /// - Remark: Generated from `#/paths//pets/multipart-typed/post(multipartUploadTyped)/responses/202`. + /// + /// HTTP response code: `202 accepted`. + case accepted(Operations.multipartUploadTyped.Output.Accepted) + /// The associated value of the enum case if `self` is `.accepted`. + /// + /// - Throws: An error if `self` is not `.accepted`. + /// - SeeAlso: `.accepted`. + public var accepted: Operations.multipartUploadTyped.Output.Accepted { + get throws { + switch self { + case let .accepted(response): + return response + default: + try throwUnexpectedResponseStatus( + expectedStatus: "accepted", + response: self + ) + } + } + } + /// Undocumented response. + /// + /// A response with a code that is not documented in the OpenAPI document. + case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) + } + } +} From 78ed2de90b01fa7a0da4aea20e0c5b9d92b6f49a Mon Sep 17 00:00:00 2001 From: Joshua Asbury <1377564+theoriginalbit@users.noreply.github.com> Date: Wed, 18 Sep 2024 20:34:27 +1000 Subject: [PATCH 03/13] Update Sources/_OpenAPIGeneratorCore/FeatureFlags.swift Co-authored-by: Honza Dvorsky --- Sources/_OpenAPIGeneratorCore/FeatureFlags.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/_OpenAPIGeneratorCore/FeatureFlags.swift b/Sources/_OpenAPIGeneratorCore/FeatureFlags.swift index 4d8bb33f..20eb7715 100644 --- a/Sources/_OpenAPIGeneratorCore/FeatureFlags.swift +++ b/Sources/_OpenAPIGeneratorCore/FeatureFlags.swift @@ -31,7 +31,7 @@ public enum FeatureFlag: String, Hashable, Codable, CaseIterable, Sendable { /// When enabled any server URL templating variables that have a defined /// enum field will be generated as an enum instead of raw Strings. - case serverVariablesAsEnums = "ServerVariablesEnums" + case serverVariablesAsEnums } /// A set of enabled feature flags. From d866ab6e3a155e5bc4f7f5e8a58729b85782386e Mon Sep 17 00:00:00 2001 From: theoriginalbit <1377564+theoriginalbit@users.noreply.github.com> Date: Wed, 18 Sep 2024 22:55:33 +1000 Subject: [PATCH 04/13] Revert addition of file-based reference test --- .../FileBasedReferenceTests.swift | 28 +- .../Client.swift | 927 ----- .../Server.swift | 1015 ------ .../Petstore_ServerVariablesEnums/Types.swift | 3071 ----------------- 4 files changed, 4 insertions(+), 5037 deletions(-) delete mode 100644 Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Client.swift delete mode 100644 Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Server.swift delete mode 100644 Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Types.swift diff --git a/Tests/OpenAPIGeneratorReferenceTests/FileBasedReferenceTests.swift b/Tests/OpenAPIGeneratorReferenceTests/FileBasedReferenceTests.swift index da496100..75b8be78 100644 --- a/Tests/OpenAPIGeneratorReferenceTests/FileBasedReferenceTests.swift +++ b/Tests/OpenAPIGeneratorReferenceTests/FileBasedReferenceTests.swift @@ -43,11 +43,6 @@ final class FileBasedReferenceTests: XCTestCase { } func testPetstore() throws { try _test(referenceProject: .init(name: .petstore)) } - - func testPetstoreWithServerVariablesEnumsFeatureFlag() throws { - let featureFlags: FeatureFlags = [.serverVariablesAsEnums] - try _test(referenceProject: .init(name: .petstore(featureFlags)), featureFlags: featureFlags) - } // MARK: - Private @@ -102,27 +97,12 @@ final class FileBasedReferenceTests: XCTestCase { ) } - enum ReferenceProjectName: Hashable { - case petstore(FeatureFlags) - - static var petstore: Self { .petstore([]) } + enum ReferenceProjectName: String, Hashable, CaseIterable { + case petstore - var openAPIDocFileName: String { - switch self { - case .petstore: - return "petstore.yaml" - } - } + var openAPIDocFileName: String { "\(rawValue).yaml" } - var fixtureCodeDirectoryName: String { - switch self { - case let .petstore(featureFlags): - if featureFlags.isEmpty { - return "Petstore" - } - return "Petstore_" + featureFlags.map(\.rawValue).joined(separator: "_") - } - } + var fixtureCodeDirectoryName: String { rawValue.capitalized } } struct ReferenceProject: Hashable { diff --git a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Client.swift b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Client.swift deleted file mode 100644 index 75c9bf22..00000000 --- a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Client.swift +++ /dev/null @@ -1,927 +0,0 @@ -// Generated by swift-openapi-generator, do not modify. -@_spi(Generated) import OpenAPIRuntime -#if os(Linux) -@preconcurrency import struct Foundation.URL -@preconcurrency import struct Foundation.Data -@preconcurrency import struct Foundation.Date -#else -import struct Foundation.URL -import struct Foundation.Data -import struct Foundation.Date -#endif -import HTTPTypes -/// Service for managing pet metadata. -/// -/// Because why not. -public struct Client: APIProtocol { - /// The underlying HTTP client. - private let client: UniversalClient - /// Creates a new client. - /// - Parameters: - /// - serverURL: The server URL that the client connects to. Any server - /// URLs defined in the OpenAPI document are available as static methods - /// on the ``Servers`` type. - /// - configuration: A set of configuration values for the client. - /// - transport: A transport that performs HTTP operations. - /// - middlewares: A list of middlewares to call before the transport. - public init( - serverURL: Foundation.URL, - configuration: Configuration = .init(), - transport: any ClientTransport, - middlewares: [any ClientMiddleware] = [] - ) { - self.client = .init( - serverURL: serverURL, - configuration: configuration, - transport: transport, - middlewares: middlewares - ) - } - private var converter: Converter { - client.converter - } - /// List all pets - /// - /// You can fetch - /// all the pets here - /// - /// - Remark: HTTP `GET /pets`. - /// - Remark: Generated from `#/paths//pets/get(listPets)`. - public func listPets(_ input: Operations.listPets.Input) async throws -> Operations.listPets.Output { - try await client.send( - input: input, - forOperation: Operations.listPets.id, - serializer: { input in - let path = try converter.renderedPath( - template: "/pets", - parameters: [] - ) - var request: HTTPTypes.HTTPRequest = .init( - soar_path: path, - method: .get - ) - suppressMutabilityWarning(&request) - try converter.setQueryItemAsURI( - in: &request, - style: .form, - explode: true, - name: "limit", - value: input.query.limit - ) - try converter.setQueryItemAsURI( - in: &request, - style: .form, - explode: true, - name: "habitat", - value: input.query.habitat - ) - try converter.setQueryItemAsURI( - in: &request, - style: .form, - explode: true, - name: "feeds", - value: input.query.feeds - ) - try converter.setHeaderFieldAsURI( - in: &request.headerFields, - name: "My-Request-UUID", - value: input.headers.My_hyphen_Request_hyphen_UUID - ) - try converter.setQueryItemAsURI( - in: &request, - style: .form, - explode: true, - name: "since", - value: input.query.since - ) - converter.setAcceptHeader( - in: &request.headerFields, - contentTypes: input.headers.accept - ) - return (request, nil) - }, - deserializer: { response, responseBody in - switch response.status.code { - case 200: - let headers: Operations.listPets.Output.Ok.Headers = .init( - My_hyphen_Response_hyphen_UUID: try converter.getRequiredHeaderFieldAsURI( - in: response.headerFields, - name: "My-Response-UUID", - as: Swift.String.self - ), - My_hyphen_Tracing_hyphen_Header: try converter.getOptionalHeaderFieldAsURI( - in: response.headerFields, - name: "My-Tracing-Header", - as: Components.Headers.TracingHeader.self - ) - ) - let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) - let body: Operations.listPets.Output.Ok.Body - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "application/json" - ] - ) - switch chosenContentType { - case "application/json": - body = try await converter.getResponseBodyAsJSON( - Components.Schemas.Pets.self, - from: responseBody, - transforming: { value in - .json(value) - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return .ok(.init( - headers: headers, - body: body - )) - default: - let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) - let body: Operations.listPets.Output.Default.Body - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "application/json" - ] - ) - switch chosenContentType { - case "application/json": - body = try await converter.getResponseBodyAsJSON( - Components.Schemas._Error.self, - from: responseBody, - transforming: { value in - .json(value) - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return .`default`( - statusCode: response.status.code, - .init(body: body) - ) - } - } - ) - } - /// Create a pet - /// - /// - Remark: HTTP `POST /pets`. - /// - Remark: Generated from `#/paths//pets/post(createPet)`. - public func createPet(_ input: Operations.createPet.Input) async throws -> Operations.createPet.Output { - try await client.send( - input: input, - forOperation: Operations.createPet.id, - serializer: { input in - let path = try converter.renderedPath( - template: "/pets", - parameters: [] - ) - var request: HTTPTypes.HTTPRequest = .init( - soar_path: path, - method: .post - ) - suppressMutabilityWarning(&request) - try converter.setHeaderFieldAsJSON( - in: &request.headerFields, - name: "X-Extra-Arguments", - value: input.headers.X_hyphen_Extra_hyphen_Arguments - ) - converter.setAcceptHeader( - in: &request.headerFields, - contentTypes: input.headers.accept - ) - let body: OpenAPIRuntime.HTTPBody? - switch input.body { - case let .json(value): - body = try converter.setRequiredRequestBodyAsJSON( - value, - headerFields: &request.headerFields, - contentType: "application/json; charset=utf-8" - ) - } - return (request, body) - }, - deserializer: { response, responseBody in - switch response.status.code { - case 201: - let headers: Operations.createPet.Output.Created.Headers = .init(X_hyphen_Extra_hyphen_Arguments: try converter.getOptionalHeaderFieldAsJSON( - in: response.headerFields, - name: "X-Extra-Arguments", - as: Components.Schemas.CodeError.self - )) - let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) - let body: Operations.createPet.Output.Created.Body - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "application/json" - ] - ) - switch chosenContentType { - case "application/json": - body = try await converter.getResponseBodyAsJSON( - Components.Schemas.Pet.self, - from: responseBody, - transforming: { value in - .json(value) - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return .created(.init( - headers: headers, - body: body - )) - case 400 ... 499: - let headers: Components.Responses.ErrorBadRequest.Headers = .init(X_hyphen_Reason: try converter.getOptionalHeaderFieldAsURI( - in: response.headerFields, - name: "X-Reason", - as: Swift.String.self - )) - let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) - let body: Components.Responses.ErrorBadRequest.Body - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "application/json" - ] - ) - switch chosenContentType { - case "application/json": - body = try await converter.getResponseBodyAsJSON( - Components.Responses.ErrorBadRequest.Body.jsonPayload.self, - from: responseBody, - transforming: { value in - .json(value) - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return .clientError( - statusCode: response.status.code, - .init( - headers: headers, - body: body - ) - ) - default: - return .undocumented( - statusCode: response.status.code, - .init( - headerFields: response.headerFields, - body: responseBody - ) - ) - } - } - ) - } - /// Create a pet using a url form - /// - /// - Remark: HTTP `POST /pets/create`. - /// - Remark: Generated from `#/paths//pets/create/post(createPetWithForm)`. - public func createPetWithForm(_ input: Operations.createPetWithForm.Input) async throws -> Operations.createPetWithForm.Output { - try await client.send( - input: input, - forOperation: Operations.createPetWithForm.id, - serializer: { input in - let path = try converter.renderedPath( - template: "/pets/create", - parameters: [] - ) - var request: HTTPTypes.HTTPRequest = .init( - soar_path: path, - method: .post - ) - suppressMutabilityWarning(&request) - let body: OpenAPIRuntime.HTTPBody? - switch input.body { - case let .urlEncodedForm(value): - body = try converter.setRequiredRequestBodyAsURLEncodedForm( - value, - headerFields: &request.headerFields, - contentType: "application/x-www-form-urlencoded" - ) - } - return (request, body) - }, - deserializer: { response, responseBody in - switch response.status.code { - case 204: - return .noContent(.init()) - default: - return .undocumented( - statusCode: response.status.code, - .init( - headerFields: response.headerFields, - body: responseBody - ) - ) - } - } - ) - } - /// - Remark: HTTP `GET /pets/stats`. - /// - Remark: Generated from `#/paths//pets/stats/get(getStats)`. - public func getStats(_ input: Operations.getStats.Input) async throws -> Operations.getStats.Output { - try await client.send( - input: input, - forOperation: Operations.getStats.id, - serializer: { input in - let path = try converter.renderedPath( - template: "/pets/stats", - parameters: [] - ) - var request: HTTPTypes.HTTPRequest = .init( - soar_path: path, - method: .get - ) - suppressMutabilityWarning(&request) - converter.setAcceptHeader( - in: &request.headerFields, - contentTypes: input.headers.accept - ) - return (request, nil) - }, - deserializer: { response, responseBody in - switch response.status.code { - case 200: - let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) - let body: Operations.getStats.Output.Ok.Body - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "application/json", - "text/plain", - "application/octet-stream" - ] - ) - switch chosenContentType { - case "application/json": - body = try await converter.getResponseBodyAsJSON( - Components.Schemas.PetStats.self, - from: responseBody, - transforming: { value in - .json(value) - } - ) - case "text/plain": - body = try converter.getResponseBodyAsBinary( - OpenAPIRuntime.HTTPBody.self, - from: responseBody, - transforming: { value in - .plainText(value) - } - ) - case "application/octet-stream": - body = try converter.getResponseBodyAsBinary( - OpenAPIRuntime.HTTPBody.self, - from: responseBody, - transforming: { value in - .binary(value) - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return .ok(.init(body: body)) - default: - return .undocumented( - statusCode: response.status.code, - .init( - headerFields: response.headerFields, - body: responseBody - ) - ) - } - } - ) - } - /// - Remark: HTTP `POST /pets/stats`. - /// - Remark: Generated from `#/paths//pets/stats/post(postStats)`. - public func postStats(_ input: Operations.postStats.Input) async throws -> Operations.postStats.Output { - try await client.send( - input: input, - forOperation: Operations.postStats.id, - serializer: { input in - let path = try converter.renderedPath( - template: "/pets/stats", - parameters: [] - ) - var request: HTTPTypes.HTTPRequest = .init( - soar_path: path, - method: .post - ) - suppressMutabilityWarning(&request) - let body: OpenAPIRuntime.HTTPBody? - switch input.body { - case let .json(value): - body = try converter.setRequiredRequestBodyAsJSON( - value, - headerFields: &request.headerFields, - contentType: "application/json; charset=utf-8" - ) - case let .plainText(value): - body = try converter.setRequiredRequestBodyAsBinary( - value, - headerFields: &request.headerFields, - contentType: "text/plain" - ) - case let .binary(value): - body = try converter.setRequiredRequestBodyAsBinary( - value, - headerFields: &request.headerFields, - contentType: "application/octet-stream" - ) - } - return (request, body) - }, - deserializer: { response, responseBody in - switch response.status.code { - case 202: - return .accepted(.init()) - default: - return .undocumented( - statusCode: response.status.code, - .init( - headerFields: response.headerFields, - body: responseBody - ) - ) - } - } - ) - } - /// - Remark: HTTP `POST /probe/`. - /// - Remark: Generated from `#/paths//probe//post(probe)`. - public func probe(_ input: Operations.probe.Input) async throws -> Operations.probe.Output { - try await client.send( - input: input, - forOperation: Operations.probe.id, - serializer: { input in - let path = try converter.renderedPath( - template: "/probe/", - parameters: [] - ) - var request: HTTPTypes.HTTPRequest = .init( - soar_path: path, - method: .post - ) - suppressMutabilityWarning(&request) - return (request, nil) - }, - deserializer: { response, responseBody in - switch response.status.code { - case 204: - return .noContent(.init()) - default: - return .undocumented( - statusCode: response.status.code, - .init( - headerFields: response.headerFields, - body: responseBody - ) - ) - } - } - ) - } - /// Update just a specific property of an existing pet. Nothing is updated if no request body is provided. - /// - /// - Remark: HTTP `PATCH /pets/{petId}`. - /// - Remark: Generated from `#/paths//pets/{petId}/patch(updatePet)`. - public func updatePet(_ input: Operations.updatePet.Input) async throws -> Operations.updatePet.Output { - try await client.send( - input: input, - forOperation: Operations.updatePet.id, - serializer: { input in - let path = try converter.renderedPath( - template: "/pets/{}", - parameters: [ - input.path.petId - ] - ) - var request: HTTPTypes.HTTPRequest = .init( - soar_path: path, - method: .patch - ) - suppressMutabilityWarning(&request) - converter.setAcceptHeader( - in: &request.headerFields, - contentTypes: input.headers.accept - ) - let body: OpenAPIRuntime.HTTPBody? - switch input.body { - case .none: - body = nil - case let .json(value): - body = try converter.setOptionalRequestBodyAsJSON( - value, - headerFields: &request.headerFields, - contentType: "application/json; charset=utf-8" - ) - } - return (request, body) - }, - deserializer: { response, responseBody in - switch response.status.code { - case 204: - return .noContent(.init()) - case 400: - let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) - let body: Operations.updatePet.Output.BadRequest.Body - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "application/json" - ] - ) - switch chosenContentType { - case "application/json": - body = try await converter.getResponseBodyAsJSON( - Operations.updatePet.Output.BadRequest.Body.jsonPayload.self, - from: responseBody, - transforming: { value in - .json(value) - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return .badRequest(.init(body: body)) - default: - return .undocumented( - statusCode: response.status.code, - .init( - headerFields: response.headerFields, - body: responseBody - ) - ) - } - } - ) - } - /// Upload an avatar - /// - /// - Remark: HTTP `PUT /pets/{petId}/avatar`. - /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)`. - public func uploadAvatarForPet(_ input: Operations.uploadAvatarForPet.Input) async throws -> Operations.uploadAvatarForPet.Output { - try await client.send( - input: input, - forOperation: Operations.uploadAvatarForPet.id, - serializer: { input in - let path = try converter.renderedPath( - template: "/pets/{}/avatar", - parameters: [ - input.path.petId - ] - ) - var request: HTTPTypes.HTTPRequest = .init( - soar_path: path, - method: .put - ) - suppressMutabilityWarning(&request) - converter.setAcceptHeader( - in: &request.headerFields, - contentTypes: input.headers.accept - ) - let body: OpenAPIRuntime.HTTPBody? - switch input.body { - case let .binary(value): - body = try converter.setRequiredRequestBodyAsBinary( - value, - headerFields: &request.headerFields, - contentType: "application/octet-stream" - ) - } - return (request, body) - }, - deserializer: { response, responseBody in - switch response.status.code { - case 200: - let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) - let body: Operations.uploadAvatarForPet.Output.Ok.Body - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "application/octet-stream" - ] - ) - switch chosenContentType { - case "application/octet-stream": - body = try converter.getResponseBodyAsBinary( - OpenAPIRuntime.HTTPBody.self, - from: responseBody, - transforming: { value in - .binary(value) - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return .ok(.init(body: body)) - case 412: - let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) - let body: Operations.uploadAvatarForPet.Output.PreconditionFailed.Body - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "application/json" - ] - ) - switch chosenContentType { - case "application/json": - body = try await converter.getResponseBodyAsJSON( - Swift.String.self, - from: responseBody, - transforming: { value in - .json(value) - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return .preconditionFailed(.init(body: body)) - case 500: - let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) - let body: Operations.uploadAvatarForPet.Output.InternalServerError.Body - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "text/plain" - ] - ) - switch chosenContentType { - case "text/plain": - body = try converter.getResponseBodyAsBinary( - OpenAPIRuntime.HTTPBody.self, - from: responseBody, - transforming: { value in - .plainText(value) - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return .internalServerError(.init(body: body)) - default: - return .undocumented( - statusCode: response.status.code, - .init( - headerFields: response.headerFields, - body: responseBody - ) - ) - } - } - ) - } - /// - Remark: HTTP `GET /pets/multipart-typed`. - /// - Remark: Generated from `#/paths//pets/multipart-typed/get(multipartDownloadTyped)`. - public func multipartDownloadTyped(_ input: Operations.multipartDownloadTyped.Input) async throws -> Operations.multipartDownloadTyped.Output { - try await client.send( - input: input, - forOperation: Operations.multipartDownloadTyped.id, - serializer: { input in - let path = try converter.renderedPath( - template: "/pets/multipart-typed", - parameters: [] - ) - var request: HTTPTypes.HTTPRequest = .init( - soar_path: path, - method: .get - ) - suppressMutabilityWarning(&request) - converter.setAcceptHeader( - in: &request.headerFields, - contentTypes: input.headers.accept - ) - return (request, nil) - }, - deserializer: { response, responseBody in - switch response.status.code { - case 200: - let contentType = converter.extractContentTypeIfPresent(in: response.headerFields) - let body: Components.Responses.MultipartDownloadTypedResponse.Body - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "multipart/form-data" - ] - ) - switch chosenContentType { - case "multipart/form-data": - body = try converter.getResponseBodyAsMultipart( - OpenAPIRuntime.MultipartBody.self, - from: responseBody, - transforming: { value in - .multipartForm(value) - }, - boundary: contentType.requiredBoundary(), - allowsUnknownParts: true, - requiredExactlyOncePartNames: [ - "log" - ], - requiredAtLeastOncePartNames: [], - atMostOncePartNames: [ - "metadata" - ], - zeroOrMoreTimesPartNames: [ - "keyword" - ], - decoding: { part in - let headerFields = part.headerFields - let (name, filename) = try converter.extractContentDispositionNameAndFilename(in: headerFields) - switch name { - case "log": - let headers: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.logPayload.Headers = .init(x_hyphen_log_hyphen_type: try converter.getOptionalHeaderFieldAsURI( - in: headerFields, - name: "x-log-type", - as: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.logPayload.Headers.x_hyphen_log_hyphen_typePayload.self - )) - try converter.verifyContentTypeIfPresent( - in: headerFields, - matches: "text/plain" - ) - let body = try converter.getResponseBodyAsBinary( - OpenAPIRuntime.HTTPBody.self, - from: part.body, - transforming: { - $0 - } - ) - return .log(.init( - payload: .init( - headers: headers, - body: body - ), - filename: filename - )) - case "metadata": - try converter.verifyContentTypeIfPresent( - in: headerFields, - matches: "application/json" - ) - let body = try await converter.getResponseBodyAsJSON( - Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.metadataPayload.bodyPayload.self, - from: part.body, - transforming: { - $0 - } - ) - return .metadata(.init( - payload: .init(body: body), - filename: filename - )) - case "keyword": - try converter.verifyContentTypeIfPresent( - in: headerFields, - matches: "text/plain" - ) - let body = try converter.getResponseBodyAsBinary( - OpenAPIRuntime.HTTPBody.self, - from: part.body, - transforming: { - $0 - } - ) - return .keyword(.init( - payload: .init(body: body), - filename: filename - )) - default: - return .undocumented(part) - } - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return .ok(.init(body: body)) - default: - return .undocumented( - statusCode: response.status.code, - .init( - headerFields: response.headerFields, - body: responseBody - ) - ) - } - } - ) - } - /// - Remark: HTTP `POST /pets/multipart-typed`. - /// - Remark: Generated from `#/paths//pets/multipart-typed/post(multipartUploadTyped)`. - public func multipartUploadTyped(_ input: Operations.multipartUploadTyped.Input) async throws -> Operations.multipartUploadTyped.Output { - try await client.send( - input: input, - forOperation: Operations.multipartUploadTyped.id, - serializer: { input in - let path = try converter.renderedPath( - template: "/pets/multipart-typed", - parameters: [] - ) - var request: HTTPTypes.HTTPRequest = .init( - soar_path: path, - method: .post - ) - suppressMutabilityWarning(&request) - let body: OpenAPIRuntime.HTTPBody? - switch input.body { - case let .multipartForm(value): - body = try converter.setRequiredRequestBodyAsMultipart( - value, - headerFields: &request.headerFields, - contentType: "multipart/form-data", - allowsUnknownParts: true, - requiredExactlyOncePartNames: [ - "log" - ], - requiredAtLeastOncePartNames: [], - atMostOncePartNames: [ - "metadata" - ], - zeroOrMoreTimesPartNames: [ - "keyword" - ], - encoding: { part in - switch part { - case let .log(wrapped): - var headerFields: HTTPTypes.HTTPFields = .init() - let value = wrapped.payload - try converter.setHeaderFieldAsURI( - in: &headerFields, - name: "x-log-type", - value: value.headers.x_hyphen_log_hyphen_type - ) - let body = try converter.setRequiredRequestBodyAsBinary( - value.body, - headerFields: &headerFields, - contentType: "text/plain" - ) - return .init( - name: "log", - filename: wrapped.filename, - headerFields: headerFields, - body: body - ) - case let .metadata(wrapped): - var headerFields: HTTPTypes.HTTPFields = .init() - let value = wrapped.payload - let body = try converter.setRequiredRequestBodyAsJSON( - value.body, - headerFields: &headerFields, - contentType: "application/json; charset=utf-8" - ) - return .init( - name: "metadata", - filename: wrapped.filename, - headerFields: headerFields, - body: body - ) - case let .keyword(wrapped): - var headerFields: HTTPTypes.HTTPFields = .init() - let value = wrapped.payload - let body = try converter.setRequiredRequestBodyAsBinary( - value.body, - headerFields: &headerFields, - contentType: "text/plain" - ) - return .init( - name: "keyword", - filename: wrapped.filename, - headerFields: headerFields, - body: body - ) - case let .undocumented(value): - return value - } - } - ) - } - return (request, body) - }, - deserializer: { response, responseBody in - switch response.status.code { - case 202: - return .accepted(.init()) - default: - return .undocumented( - statusCode: response.status.code, - .init( - headerFields: response.headerFields, - body: responseBody - ) - ) - } - } - ) - } -} diff --git a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Server.swift b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Server.swift deleted file mode 100644 index 80d642b3..00000000 --- a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Server.swift +++ /dev/null @@ -1,1015 +0,0 @@ -// Generated by swift-openapi-generator, do not modify. -@_spi(Generated) import OpenAPIRuntime -#if os(Linux) -@preconcurrency import struct Foundation.URL -@preconcurrency import struct Foundation.Data -@preconcurrency import struct Foundation.Date -#else -import struct Foundation.URL -import struct Foundation.Data -import struct Foundation.Date -#endif -import HTTPTypes -extension APIProtocol { - /// Registers each operation handler with the provided transport. - /// - Parameters: - /// - transport: A transport to which to register the operation handlers. - /// - serverURL: A URL used to determine the path prefix for registered - /// request handlers. - /// - configuration: A set of configuration values for the server. - /// - middlewares: A list of middlewares to call before the handler. - public func registerHandlers( - on transport: any ServerTransport, - serverURL: Foundation.URL = .defaultOpenAPIServerURL, - configuration: Configuration = .init(), - middlewares: [any ServerMiddleware] = [] - ) throws { - let server = UniversalServer( - serverURL: serverURL, - handler: self, - configuration: configuration, - middlewares: middlewares - ) - try transport.register( - { - try await server.listPets( - request: $0, - body: $1, - metadata: $2 - ) - }, - method: .get, - path: server.apiPathComponentsWithServerPrefix("/pets") - ) - try transport.register( - { - try await server.createPet( - request: $0, - body: $1, - metadata: $2 - ) - }, - method: .post, - path: server.apiPathComponentsWithServerPrefix("/pets") - ) - try transport.register( - { - try await server.createPetWithForm( - request: $0, - body: $1, - metadata: $2 - ) - }, - method: .post, - path: server.apiPathComponentsWithServerPrefix("/pets/create") - ) - try transport.register( - { - try await server.getStats( - request: $0, - body: $1, - metadata: $2 - ) - }, - method: .get, - path: server.apiPathComponentsWithServerPrefix("/pets/stats") - ) - try transport.register( - { - try await server.postStats( - request: $0, - body: $1, - metadata: $2 - ) - }, - method: .post, - path: server.apiPathComponentsWithServerPrefix("/pets/stats") - ) - try transport.register( - { - try await server.probe( - request: $0, - body: $1, - metadata: $2 - ) - }, - method: .post, - path: server.apiPathComponentsWithServerPrefix("/probe/") - ) - try transport.register( - { - try await server.updatePet( - request: $0, - body: $1, - metadata: $2 - ) - }, - method: .patch, - path: server.apiPathComponentsWithServerPrefix("/pets/{petId}") - ) - try transport.register( - { - try await server.uploadAvatarForPet( - request: $0, - body: $1, - metadata: $2 - ) - }, - method: .put, - path: server.apiPathComponentsWithServerPrefix("/pets/{petId}/avatar") - ) - try transport.register( - { - try await server.multipartDownloadTyped( - request: $0, - body: $1, - metadata: $2 - ) - }, - method: .get, - path: server.apiPathComponentsWithServerPrefix("/pets/multipart-typed") - ) - try transport.register( - { - try await server.multipartUploadTyped( - request: $0, - body: $1, - metadata: $2 - ) - }, - method: .post, - path: server.apiPathComponentsWithServerPrefix("/pets/multipart-typed") - ) - } -} - -fileprivate extension UniversalServer where APIHandler: APIProtocol { - /// List all pets - /// - /// You can fetch - /// all the pets here - /// - /// - Remark: HTTP `GET /pets`. - /// - Remark: Generated from `#/paths//pets/get(listPets)`. - func listPets( - request: HTTPTypes.HTTPRequest, - body: OpenAPIRuntime.HTTPBody?, - metadata: OpenAPIRuntime.ServerRequestMetadata - ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { - try await handle( - request: request, - requestBody: body, - metadata: metadata, - forOperation: Operations.listPets.id, - using: { - APIHandler.listPets($0) - }, - deserializer: { request, requestBody, metadata in - let query: Operations.listPets.Input.Query = .init( - limit: try converter.getOptionalQueryItemAsURI( - in: request.soar_query, - style: .form, - explode: true, - name: "limit", - as: Swift.Int32.self - ), - habitat: try converter.getOptionalQueryItemAsURI( - in: request.soar_query, - style: .form, - explode: true, - name: "habitat", - as: Operations.listPets.Input.Query.habitatPayload.self - ), - feeds: try converter.getOptionalQueryItemAsURI( - in: request.soar_query, - style: .form, - explode: true, - name: "feeds", - as: Operations.listPets.Input.Query.feedsPayload.self - ), - since: try converter.getOptionalQueryItemAsURI( - in: request.soar_query, - style: .form, - explode: true, - name: "since", - as: Components.Parameters.query_period_born_hyphen_since.self - ) - ) - let headers: Operations.listPets.Input.Headers = .init( - My_hyphen_Request_hyphen_UUID: try converter.getOptionalHeaderFieldAsURI( - in: request.headerFields, - name: "My-Request-UUID", - as: Swift.String.self - ), - accept: try converter.extractAcceptHeaderIfPresent(in: request.headerFields) - ) - return Operations.listPets.Input( - query: query, - headers: headers - ) - }, - serializer: { output, request in - switch output { - case let .ok(value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: 200) - suppressMutabilityWarning(&response) - try converter.setHeaderFieldAsURI( - in: &response.headerFields, - name: "My-Response-UUID", - value: value.headers.My_hyphen_Response_hyphen_UUID - ) - try converter.setHeaderFieldAsURI( - in: &response.headerFields, - name: "My-Tracing-Header", - value: value.headers.My_hyphen_Tracing_hyphen_Header - ) - let body: OpenAPIRuntime.HTTPBody - switch value.body { - case let .json(value): - try converter.validateAcceptIfPresent( - "application/json", - in: request.headerFields - ) - body = try converter.setResponseBodyAsJSON( - value, - headerFields: &response.headerFields, - contentType: "application/json; charset=utf-8" - ) - } - return (response, body) - case let .`default`(statusCode, value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: statusCode) - suppressMutabilityWarning(&response) - let body: OpenAPIRuntime.HTTPBody - switch value.body { - case let .json(value): - try converter.validateAcceptIfPresent( - "application/json", - in: request.headerFields - ) - body = try converter.setResponseBodyAsJSON( - value, - headerFields: &response.headerFields, - contentType: "application/json; charset=utf-8" - ) - } - return (response, body) - } - } - ) - } - /// Create a pet - /// - /// - Remark: HTTP `POST /pets`. - /// - Remark: Generated from `#/paths//pets/post(createPet)`. - func createPet( - request: HTTPTypes.HTTPRequest, - body: OpenAPIRuntime.HTTPBody?, - metadata: OpenAPIRuntime.ServerRequestMetadata - ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { - try await handle( - request: request, - requestBody: body, - metadata: metadata, - forOperation: Operations.createPet.id, - using: { - APIHandler.createPet($0) - }, - deserializer: { request, requestBody, metadata in - let headers: Operations.createPet.Input.Headers = .init( - X_hyphen_Extra_hyphen_Arguments: try converter.getOptionalHeaderFieldAsJSON( - in: request.headerFields, - name: "X-Extra-Arguments", - as: Components.Schemas.CodeError.self - ), - accept: try converter.extractAcceptHeaderIfPresent(in: request.headerFields) - ) - let contentType = converter.extractContentTypeIfPresent(in: request.headerFields) - let body: Operations.createPet.Input.Body - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "application/json" - ] - ) - switch chosenContentType { - case "application/json": - body = try await converter.getRequiredRequestBodyAsJSON( - Components.Schemas.CreatePetRequest.self, - from: requestBody, - transforming: { value in - .json(value) - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return Operations.createPet.Input( - headers: headers, - body: body - ) - }, - serializer: { output, request in - switch output { - case let .created(value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: 201) - suppressMutabilityWarning(&response) - try converter.setHeaderFieldAsJSON( - in: &response.headerFields, - name: "X-Extra-Arguments", - value: value.headers.X_hyphen_Extra_hyphen_Arguments - ) - let body: OpenAPIRuntime.HTTPBody - switch value.body { - case let .json(value): - try converter.validateAcceptIfPresent( - "application/json", - in: request.headerFields - ) - body = try converter.setResponseBodyAsJSON( - value, - headerFields: &response.headerFields, - contentType: "application/json; charset=utf-8" - ) - } - return (response, body) - case let .clientError(statusCode, value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: statusCode) - suppressMutabilityWarning(&response) - try converter.setHeaderFieldAsURI( - in: &response.headerFields, - name: "X-Reason", - value: value.headers.X_hyphen_Reason - ) - let body: OpenAPIRuntime.HTTPBody - switch value.body { - case let .json(value): - try converter.validateAcceptIfPresent( - "application/json", - in: request.headerFields - ) - body = try converter.setResponseBodyAsJSON( - value, - headerFields: &response.headerFields, - contentType: "application/json; charset=utf-8" - ) - } - return (response, body) - case let .undocumented(statusCode, _): - return (.init(soar_statusCode: statusCode), nil) - } - } - ) - } - /// Create a pet using a url form - /// - /// - Remark: HTTP `POST /pets/create`. - /// - Remark: Generated from `#/paths//pets/create/post(createPetWithForm)`. - func createPetWithForm( - request: HTTPTypes.HTTPRequest, - body: OpenAPIRuntime.HTTPBody?, - metadata: OpenAPIRuntime.ServerRequestMetadata - ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { - try await handle( - request: request, - requestBody: body, - metadata: metadata, - forOperation: Operations.createPetWithForm.id, - using: { - APIHandler.createPetWithForm($0) - }, - deserializer: { request, requestBody, metadata in - let contentType = converter.extractContentTypeIfPresent(in: request.headerFields) - let body: Operations.createPetWithForm.Input.Body - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "application/x-www-form-urlencoded" - ] - ) - switch chosenContentType { - case "application/x-www-form-urlencoded": - body = try await converter.getRequiredRequestBodyAsURLEncodedForm( - Components.Schemas.CreatePetRequest.self, - from: requestBody, - transforming: { value in - .urlEncodedForm(value) - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return Operations.createPetWithForm.Input(body: body) - }, - serializer: { output, request in - switch output { - case let .noContent(value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: 204) - suppressMutabilityWarning(&response) - return (response, nil) - case let .undocumented(statusCode, _): - return (.init(soar_statusCode: statusCode), nil) - } - } - ) - } - /// - Remark: HTTP `GET /pets/stats`. - /// - Remark: Generated from `#/paths//pets/stats/get(getStats)`. - func getStats( - request: HTTPTypes.HTTPRequest, - body: OpenAPIRuntime.HTTPBody?, - metadata: OpenAPIRuntime.ServerRequestMetadata - ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { - try await handle( - request: request, - requestBody: body, - metadata: metadata, - forOperation: Operations.getStats.id, - using: { - APIHandler.getStats($0) - }, - deserializer: { request, requestBody, metadata in - let headers: Operations.getStats.Input.Headers = .init(accept: try converter.extractAcceptHeaderIfPresent(in: request.headerFields)) - return Operations.getStats.Input(headers: headers) - }, - serializer: { output, request in - switch output { - case let .ok(value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: 200) - suppressMutabilityWarning(&response) - let body: OpenAPIRuntime.HTTPBody - switch value.body { - case let .json(value): - try converter.validateAcceptIfPresent( - "application/json", - in: request.headerFields - ) - body = try converter.setResponseBodyAsJSON( - value, - headerFields: &response.headerFields, - contentType: "application/json; charset=utf-8" - ) - case let .plainText(value): - try converter.validateAcceptIfPresent( - "text/plain", - in: request.headerFields - ) - body = try converter.setResponseBodyAsBinary( - value, - headerFields: &response.headerFields, - contentType: "text/plain" - ) - case let .binary(value): - try converter.validateAcceptIfPresent( - "application/octet-stream", - in: request.headerFields - ) - body = try converter.setResponseBodyAsBinary( - value, - headerFields: &response.headerFields, - contentType: "application/octet-stream" - ) - } - return (response, body) - case let .undocumented(statusCode, _): - return (.init(soar_statusCode: statusCode), nil) - } - } - ) - } - /// - Remark: HTTP `POST /pets/stats`. - /// - Remark: Generated from `#/paths//pets/stats/post(postStats)`. - func postStats( - request: HTTPTypes.HTTPRequest, - body: OpenAPIRuntime.HTTPBody?, - metadata: OpenAPIRuntime.ServerRequestMetadata - ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { - try await handle( - request: request, - requestBody: body, - metadata: metadata, - forOperation: Operations.postStats.id, - using: { - APIHandler.postStats($0) - }, - deserializer: { request, requestBody, metadata in - let contentType = converter.extractContentTypeIfPresent(in: request.headerFields) - let body: Operations.postStats.Input.Body - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "application/json", - "text/plain", - "application/octet-stream" - ] - ) - switch chosenContentType { - case "application/json": - body = try await converter.getRequiredRequestBodyAsJSON( - Components.Schemas.PetStats.self, - from: requestBody, - transforming: { value in - .json(value) - } - ) - case "text/plain": - body = try converter.getRequiredRequestBodyAsBinary( - OpenAPIRuntime.HTTPBody.self, - from: requestBody, - transforming: { value in - .plainText(value) - } - ) - case "application/octet-stream": - body = try converter.getRequiredRequestBodyAsBinary( - OpenAPIRuntime.HTTPBody.self, - from: requestBody, - transforming: { value in - .binary(value) - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return Operations.postStats.Input(body: body) - }, - serializer: { output, request in - switch output { - case let .accepted(value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: 202) - suppressMutabilityWarning(&response) - return (response, nil) - case let .undocumented(statusCode, _): - return (.init(soar_statusCode: statusCode), nil) - } - } - ) - } - /// - Remark: HTTP `POST /probe/`. - /// - Remark: Generated from `#/paths//probe//post(probe)`. - func probe( - request: HTTPTypes.HTTPRequest, - body: OpenAPIRuntime.HTTPBody?, - metadata: OpenAPIRuntime.ServerRequestMetadata - ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { - try await handle( - request: request, - requestBody: body, - metadata: metadata, - forOperation: Operations.probe.id, - using: { - APIHandler.probe($0) - }, - deserializer: { request, requestBody, metadata in - return Operations.probe.Input() - }, - serializer: { output, request in - switch output { - case let .noContent(value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: 204) - suppressMutabilityWarning(&response) - return (response, nil) - case let .undocumented(statusCode, _): - return (.init(soar_statusCode: statusCode), nil) - } - } - ) - } - /// Update just a specific property of an existing pet. Nothing is updated if no request body is provided. - /// - /// - Remark: HTTP `PATCH /pets/{petId}`. - /// - Remark: Generated from `#/paths//pets/{petId}/patch(updatePet)`. - func updatePet( - request: HTTPTypes.HTTPRequest, - body: OpenAPIRuntime.HTTPBody?, - metadata: OpenAPIRuntime.ServerRequestMetadata - ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { - try await handle( - request: request, - requestBody: body, - metadata: metadata, - forOperation: Operations.updatePet.id, - using: { - APIHandler.updatePet($0) - }, - deserializer: { request, requestBody, metadata in - let path: Operations.updatePet.Input.Path = .init(petId: try converter.getPathParameterAsURI( - in: metadata.pathParameters, - name: "petId", - as: Swift.Int64.self - )) - let headers: Operations.updatePet.Input.Headers = .init(accept: try converter.extractAcceptHeaderIfPresent(in: request.headerFields)) - let contentType = converter.extractContentTypeIfPresent(in: request.headerFields) - let body: Components.RequestBodies.UpdatePetRequest? - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "application/json" - ] - ) - switch chosenContentType { - case "application/json": - body = try await converter.getOptionalRequestBodyAsJSON( - Components.RequestBodies.UpdatePetRequest.jsonPayload.self, - from: requestBody, - transforming: { value in - .json(value) - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return Operations.updatePet.Input( - path: path, - headers: headers, - body: body - ) - }, - serializer: { output, request in - switch output { - case let .noContent(value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: 204) - suppressMutabilityWarning(&response) - return (response, nil) - case let .badRequest(value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: 400) - suppressMutabilityWarning(&response) - let body: OpenAPIRuntime.HTTPBody - switch value.body { - case let .json(value): - try converter.validateAcceptIfPresent( - "application/json", - in: request.headerFields - ) - body = try converter.setResponseBodyAsJSON( - value, - headerFields: &response.headerFields, - contentType: "application/json; charset=utf-8" - ) - } - return (response, body) - case let .undocumented(statusCode, _): - return (.init(soar_statusCode: statusCode), nil) - } - } - ) - } - /// Upload an avatar - /// - /// - Remark: HTTP `PUT /pets/{petId}/avatar`. - /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)`. - func uploadAvatarForPet( - request: HTTPTypes.HTTPRequest, - body: OpenAPIRuntime.HTTPBody?, - metadata: OpenAPIRuntime.ServerRequestMetadata - ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { - try await handle( - request: request, - requestBody: body, - metadata: metadata, - forOperation: Operations.uploadAvatarForPet.id, - using: { - APIHandler.uploadAvatarForPet($0) - }, - deserializer: { request, requestBody, metadata in - let path: Operations.uploadAvatarForPet.Input.Path = .init(petId: try converter.getPathParameterAsURI( - in: metadata.pathParameters, - name: "petId", - as: Components.Parameters.path_period_petId.self - )) - let headers: Operations.uploadAvatarForPet.Input.Headers = .init(accept: try converter.extractAcceptHeaderIfPresent(in: request.headerFields)) - let contentType = converter.extractContentTypeIfPresent(in: request.headerFields) - let body: Operations.uploadAvatarForPet.Input.Body - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "application/octet-stream" - ] - ) - switch chosenContentType { - case "application/octet-stream": - body = try converter.getRequiredRequestBodyAsBinary( - OpenAPIRuntime.HTTPBody.self, - from: requestBody, - transforming: { value in - .binary(value) - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return Operations.uploadAvatarForPet.Input( - path: path, - headers: headers, - body: body - ) - }, - serializer: { output, request in - switch output { - case let .ok(value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: 200) - suppressMutabilityWarning(&response) - let body: OpenAPIRuntime.HTTPBody - switch value.body { - case let .binary(value): - try converter.validateAcceptIfPresent( - "application/octet-stream", - in: request.headerFields - ) - body = try converter.setResponseBodyAsBinary( - value, - headerFields: &response.headerFields, - contentType: "application/octet-stream" - ) - } - return (response, body) - case let .preconditionFailed(value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: 412) - suppressMutabilityWarning(&response) - let body: OpenAPIRuntime.HTTPBody - switch value.body { - case let .json(value): - try converter.validateAcceptIfPresent( - "application/json", - in: request.headerFields - ) - body = try converter.setResponseBodyAsJSON( - value, - headerFields: &response.headerFields, - contentType: "application/json; charset=utf-8" - ) - } - return (response, body) - case let .internalServerError(value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: 500) - suppressMutabilityWarning(&response) - let body: OpenAPIRuntime.HTTPBody - switch value.body { - case let .plainText(value): - try converter.validateAcceptIfPresent( - "text/plain", - in: request.headerFields - ) - body = try converter.setResponseBodyAsBinary( - value, - headerFields: &response.headerFields, - contentType: "text/plain" - ) - } - return (response, body) - case let .undocumented(statusCode, _): - return (.init(soar_statusCode: statusCode), nil) - } - } - ) - } - /// - Remark: HTTP `GET /pets/multipart-typed`. - /// - Remark: Generated from `#/paths//pets/multipart-typed/get(multipartDownloadTyped)`. - func multipartDownloadTyped( - request: HTTPTypes.HTTPRequest, - body: OpenAPIRuntime.HTTPBody?, - metadata: OpenAPIRuntime.ServerRequestMetadata - ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { - try await handle( - request: request, - requestBody: body, - metadata: metadata, - forOperation: Operations.multipartDownloadTyped.id, - using: { - APIHandler.multipartDownloadTyped($0) - }, - deserializer: { request, requestBody, metadata in - let headers: Operations.multipartDownloadTyped.Input.Headers = .init(accept: try converter.extractAcceptHeaderIfPresent(in: request.headerFields)) - return Operations.multipartDownloadTyped.Input(headers: headers) - }, - serializer: { output, request in - switch output { - case let .ok(value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: 200) - suppressMutabilityWarning(&response) - let body: OpenAPIRuntime.HTTPBody - switch value.body { - case let .multipartForm(value): - try converter.validateAcceptIfPresent( - "multipart/form-data", - in: request.headerFields - ) - body = try converter.setResponseBodyAsMultipart( - value, - headerFields: &response.headerFields, - contentType: "multipart/form-data", - allowsUnknownParts: true, - requiredExactlyOncePartNames: [ - "log" - ], - requiredAtLeastOncePartNames: [], - atMostOncePartNames: [ - "metadata" - ], - zeroOrMoreTimesPartNames: [ - "keyword" - ], - encoding: { part in - switch part { - case let .log(wrapped): - var headerFields: HTTPTypes.HTTPFields = .init() - let value = wrapped.payload - try converter.setHeaderFieldAsURI( - in: &headerFields, - name: "x-log-type", - value: value.headers.x_hyphen_log_hyphen_type - ) - let body = try converter.setResponseBodyAsBinary( - value.body, - headerFields: &headerFields, - contentType: "text/plain" - ) - return .init( - name: "log", - filename: wrapped.filename, - headerFields: headerFields, - body: body - ) - case let .metadata(wrapped): - var headerFields: HTTPTypes.HTTPFields = .init() - let value = wrapped.payload - let body = try converter.setResponseBodyAsJSON( - value.body, - headerFields: &headerFields, - contentType: "application/json; charset=utf-8" - ) - return .init( - name: "metadata", - filename: wrapped.filename, - headerFields: headerFields, - body: body - ) - case let .keyword(wrapped): - var headerFields: HTTPTypes.HTTPFields = .init() - let value = wrapped.payload - let body = try converter.setResponseBodyAsBinary( - value.body, - headerFields: &headerFields, - contentType: "text/plain" - ) - return .init( - name: "keyword", - filename: wrapped.filename, - headerFields: headerFields, - body: body - ) - case let .undocumented(value): - return value - } - } - ) - } - return (response, body) - case let .undocumented(statusCode, _): - return (.init(soar_statusCode: statusCode), nil) - } - } - ) - } - /// - Remark: HTTP `POST /pets/multipart-typed`. - /// - Remark: Generated from `#/paths//pets/multipart-typed/post(multipartUploadTyped)`. - func multipartUploadTyped( - request: HTTPTypes.HTTPRequest, - body: OpenAPIRuntime.HTTPBody?, - metadata: OpenAPIRuntime.ServerRequestMetadata - ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { - try await handle( - request: request, - requestBody: body, - metadata: metadata, - forOperation: Operations.multipartUploadTyped.id, - using: { - APIHandler.multipartUploadTyped($0) - }, - deserializer: { request, requestBody, metadata in - let contentType = converter.extractContentTypeIfPresent(in: request.headerFields) - let body: Components.RequestBodies.MultipartUploadTypedRequest - let chosenContentType = try converter.bestContentType( - received: contentType, - options: [ - "multipart/form-data" - ] - ) - switch chosenContentType { - case "multipart/form-data": - body = try converter.getRequiredRequestBodyAsMultipart( - OpenAPIRuntime.MultipartBody.self, - from: requestBody, - transforming: { value in - .multipartForm(value) - }, - boundary: contentType.requiredBoundary(), - allowsUnknownParts: true, - requiredExactlyOncePartNames: [ - "log" - ], - requiredAtLeastOncePartNames: [], - atMostOncePartNames: [ - "metadata" - ], - zeroOrMoreTimesPartNames: [ - "keyword" - ], - decoding: { part in - let headerFields = part.headerFields - let (name, filename) = try converter.extractContentDispositionNameAndFilename(in: headerFields) - switch name { - case "log": - let headers: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.logPayload.Headers = .init(x_hyphen_log_hyphen_type: try converter.getOptionalHeaderFieldAsURI( - in: headerFields, - name: "x-log-type", - as: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.logPayload.Headers.x_hyphen_log_hyphen_typePayload.self - )) - try converter.verifyContentTypeIfPresent( - in: headerFields, - matches: "text/plain" - ) - let body = try converter.getRequiredRequestBodyAsBinary( - OpenAPIRuntime.HTTPBody.self, - from: part.body, - transforming: { - $0 - } - ) - return .log(.init( - payload: .init( - headers: headers, - body: body - ), - filename: filename - )) - case "metadata": - try converter.verifyContentTypeIfPresent( - in: headerFields, - matches: "application/json" - ) - let body = try await converter.getRequiredRequestBodyAsJSON( - Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.metadataPayload.bodyPayload.self, - from: part.body, - transforming: { - $0 - } - ) - return .metadata(.init( - payload: .init(body: body), - filename: filename - )) - case "keyword": - try converter.verifyContentTypeIfPresent( - in: headerFields, - matches: "text/plain" - ) - let body = try converter.getRequiredRequestBodyAsBinary( - OpenAPIRuntime.HTTPBody.self, - from: part.body, - transforming: { - $0 - } - ) - return .keyword(.init( - payload: .init(body: body), - filename: filename - )) - default: - return .undocumented(part) - } - } - ) - default: - preconditionFailure("bestContentType chose an invalid content type.") - } - return Operations.multipartUploadTyped.Input(body: body) - }, - serializer: { output, request in - switch output { - case let .accepted(value): - suppressUnusedWarning(value) - var response = HTTPTypes.HTTPResponse(soar_statusCode: 202) - suppressMutabilityWarning(&response) - return (response, nil) - case let .undocumented(statusCode, _): - return (.init(soar_statusCode: statusCode), nil) - } - } - ) - } -} diff --git a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Types.swift b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Types.swift deleted file mode 100644 index 608dc287..00000000 --- a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore_ServerVariablesEnums/Types.swift +++ /dev/null @@ -1,3071 +0,0 @@ -// Generated by swift-openapi-generator, do not modify. -@_spi(Generated) import OpenAPIRuntime -#if os(Linux) -@preconcurrency import struct Foundation.URL -@preconcurrency import struct Foundation.Data -@preconcurrency import struct Foundation.Date -#else -import struct Foundation.URL -import struct Foundation.Data -import struct Foundation.Date -#endif -/// A type that performs HTTP operations defined by the OpenAPI document. -public protocol APIProtocol: Sendable { - /// List all pets - /// - /// You can fetch - /// all the pets here - /// - /// - Remark: HTTP `GET /pets`. - /// - Remark: Generated from `#/paths//pets/get(listPets)`. - func listPets(_ input: Operations.listPets.Input) async throws -> Operations.listPets.Output - /// Create a pet - /// - /// - Remark: HTTP `POST /pets`. - /// - Remark: Generated from `#/paths//pets/post(createPet)`. - func createPet(_ input: Operations.createPet.Input) async throws -> Operations.createPet.Output - /// Create a pet using a url form - /// - /// - Remark: HTTP `POST /pets/create`. - /// - Remark: Generated from `#/paths//pets/create/post(createPetWithForm)`. - func createPetWithForm(_ input: Operations.createPetWithForm.Input) async throws -> Operations.createPetWithForm.Output - /// - Remark: HTTP `GET /pets/stats`. - /// - Remark: Generated from `#/paths//pets/stats/get(getStats)`. - func getStats(_ input: Operations.getStats.Input) async throws -> Operations.getStats.Output - /// - Remark: HTTP `POST /pets/stats`. - /// - Remark: Generated from `#/paths//pets/stats/post(postStats)`. - func postStats(_ input: Operations.postStats.Input) async throws -> Operations.postStats.Output - /// - Remark: HTTP `POST /probe/`. - /// - Remark: Generated from `#/paths//probe//post(probe)`. - func probe(_ input: Operations.probe.Input) async throws -> Operations.probe.Output - /// Update just a specific property of an existing pet. Nothing is updated if no request body is provided. - /// - /// - Remark: HTTP `PATCH /pets/{petId}`. - /// - Remark: Generated from `#/paths//pets/{petId}/patch(updatePet)`. - func updatePet(_ input: Operations.updatePet.Input) async throws -> Operations.updatePet.Output - /// Upload an avatar - /// - /// - Remark: HTTP `PUT /pets/{petId}/avatar`. - /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)`. - func uploadAvatarForPet(_ input: Operations.uploadAvatarForPet.Input) async throws -> Operations.uploadAvatarForPet.Output - /// - Remark: HTTP `GET /pets/multipart-typed`. - /// - Remark: Generated from `#/paths//pets/multipart-typed/get(multipartDownloadTyped)`. - func multipartDownloadTyped(_ input: Operations.multipartDownloadTyped.Input) async throws -> Operations.multipartDownloadTyped.Output - /// - Remark: HTTP `POST /pets/multipart-typed`. - /// - Remark: Generated from `#/paths//pets/multipart-typed/post(multipartUploadTyped)`. - func multipartUploadTyped(_ input: Operations.multipartUploadTyped.Input) async throws -> Operations.multipartUploadTyped.Output -} - -/// Convenience overloads for operation inputs. -extension APIProtocol { - /// List all pets - /// - /// You can fetch - /// all the pets here - /// - /// - Remark: HTTP `GET /pets`. - /// - Remark: Generated from `#/paths//pets/get(listPets)`. - public func listPets( - query: Operations.listPets.Input.Query = .init(), - headers: Operations.listPets.Input.Headers = .init() - ) async throws -> Operations.listPets.Output { - try await listPets(Operations.listPets.Input( - query: query, - headers: headers - )) - } - /// Create a pet - /// - /// - Remark: HTTP `POST /pets`. - /// - Remark: Generated from `#/paths//pets/post(createPet)`. - public func createPet( - headers: Operations.createPet.Input.Headers = .init(), - body: Operations.createPet.Input.Body - ) async throws -> Operations.createPet.Output { - try await createPet(Operations.createPet.Input( - headers: headers, - body: body - )) - } - /// Create a pet using a url form - /// - /// - Remark: HTTP `POST /pets/create`. - /// - Remark: Generated from `#/paths//pets/create/post(createPetWithForm)`. - public func createPetWithForm(body: Operations.createPetWithForm.Input.Body) async throws -> Operations.createPetWithForm.Output { - try await createPetWithForm(Operations.createPetWithForm.Input(body: body)) - } - /// - Remark: HTTP `GET /pets/stats`. - /// - Remark: Generated from `#/paths//pets/stats/get(getStats)`. - public func getStats(headers: Operations.getStats.Input.Headers = .init()) async throws -> Operations.getStats.Output { - try await getStats(Operations.getStats.Input(headers: headers)) - } - /// - Remark: HTTP `POST /pets/stats`. - /// - Remark: Generated from `#/paths//pets/stats/post(postStats)`. - public func postStats(body: Operations.postStats.Input.Body) async throws -> Operations.postStats.Output { - try await postStats(Operations.postStats.Input(body: body)) - } - /// - Remark: HTTP `POST /probe/`. - /// - Remark: Generated from `#/paths//probe//post(probe)`. - public func probe() async throws -> Operations.probe.Output { - try await probe(Operations.probe.Input()) - } - /// Update just a specific property of an existing pet. Nothing is updated if no request body is provided. - /// - /// - Remark: HTTP `PATCH /pets/{petId}`. - /// - Remark: Generated from `#/paths//pets/{petId}/patch(updatePet)`. - public func updatePet( - path: Operations.updatePet.Input.Path, - headers: Operations.updatePet.Input.Headers = .init(), - body: Components.RequestBodies.UpdatePetRequest? = nil - ) async throws -> Operations.updatePet.Output { - try await updatePet(Operations.updatePet.Input( - path: path, - headers: headers, - body: body - )) - } - /// Upload an avatar - /// - /// - Remark: HTTP `PUT /pets/{petId}/avatar`. - /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)`. - public func uploadAvatarForPet( - path: Operations.uploadAvatarForPet.Input.Path, - headers: Operations.uploadAvatarForPet.Input.Headers = .init(), - body: Operations.uploadAvatarForPet.Input.Body - ) async throws -> Operations.uploadAvatarForPet.Output { - try await uploadAvatarForPet(Operations.uploadAvatarForPet.Input( - path: path, - headers: headers, - body: body - )) - } - /// - Remark: HTTP `GET /pets/multipart-typed`. - /// - Remark: Generated from `#/paths//pets/multipart-typed/get(multipartDownloadTyped)`. - public func multipartDownloadTyped(headers: Operations.multipartDownloadTyped.Input.Headers = .init()) async throws -> Operations.multipartDownloadTyped.Output { - try await multipartDownloadTyped(Operations.multipartDownloadTyped.Input(headers: headers)) - } - /// - Remark: HTTP `POST /pets/multipart-typed`. - /// - Remark: Generated from `#/paths//pets/multipart-typed/post(multipartUploadTyped)`. - public func multipartUploadTyped(body: Components.RequestBodies.MultipartUploadTypedRequest) async throws -> Operations.multipartUploadTyped.Output { - try await multipartUploadTyped(Operations.multipartUploadTyped.Input(body: body)) - } -} - -/// Server URLs defined in the OpenAPI document. -public enum Servers { - /// Server URL variables defined in the OpenAPI document. - public enum Variables { - /// The variables for Server3 defined in the OpenAPI document. - public enum Server3 { - /// The "port" variable defined in the OpenAPI document. The default value is "443". - @frozen public enum Port: Swift.String { - case _443 = "443" - case _8443 = "8443" - /// The default variable. - public static var `default`: Port { - return Port._443 - } - } - } - } - /// Example Petstore implementation service - public static func server1() throws -> Foundation.URL { - try Foundation.URL( - validatingOpenAPIServerURL: "https://example.com/api", - variables: [] - ) - } - public static func server2() throws -> Foundation.URL { - try Foundation.URL( - validatingOpenAPIServerURL: "/api", - variables: [] - ) - } - /// A custom domain. - /// - /// - Parameters: - /// - _protocol: - /// - subdomain: A subdomain name. - /// - port: - /// - basePath: The base API path. - public static func server3( - _protocol: Swift.String = "https", - subdomain: Swift.String = "test", - port: Variables.Server3.Port = Variables.Server3.Port.default, - basePath: Swift.String = "v1" - ) throws -> Foundation.URL { - try Foundation.URL( - validatingOpenAPIServerURL: "{protocol}://{subdomain}.example.com:{port}/{basePath}", - variables: [ - .init( - name: "protocol", - value: _protocol - ), - .init( - name: "subdomain", - value: subdomain - ), - .init( - name: "port", - value: port.rawValue - ), - .init( - name: "basePath", - value: basePath - ) - ] - ) - } -} - -/// Types generated from the components section of the OpenAPI document. -public enum Components { - /// Types generated from the `#/components/schemas` section of the OpenAPI document. - public enum Schemas { - /// Pet metadata - /// - /// - Remark: Generated from `#/components/schemas/Pet`. - public struct Pet: Codable, Hashable, Sendable { - /// Pet id - /// - /// - Remark: Generated from `#/components/schemas/Pet/id`. - public var id: Swift.Int64 - /// Pet name - /// - /// - Remark: Generated from `#/components/schemas/Pet/name`. - public var name: Swift.String - /// - Remark: Generated from `#/components/schemas/Pet/tag`. - public var tag: Swift.String? - /// Pet genome (base64-encoded) - /// - /// - Remark: Generated from `#/components/schemas/Pet/genome`. - public var genome: OpenAPIRuntime.Base64EncodedData? - /// - Remark: Generated from `#/components/schemas/Pet/kind`. - public var kind: Components.Schemas.PetKind? - /// Creates a new `Pet`. - /// - /// - Parameters: - /// - id: Pet id - /// - name: Pet name - /// - tag: - /// - genome: Pet genome (base64-encoded) - /// - kind: - public init( - id: Swift.Int64, - name: Swift.String, - tag: Swift.String? = nil, - genome: OpenAPIRuntime.Base64EncodedData? = nil, - kind: Components.Schemas.PetKind? = nil - ) { - self.id = id - self.name = name - self.tag = tag - self.genome = genome - self.kind = kind - } - public enum CodingKeys: String, CodingKey { - case id - case name - case tag - case genome - case kind - } - } - /// - Remark: Generated from `#/components/schemas/MixedAnyOf`. - public struct MixedAnyOf: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/MixedAnyOf/value1`. - public var value1: Foundation.Date? - /// - Remark: Generated from `#/components/schemas/MixedAnyOf/value2`. - public var value2: Components.Schemas.PetKind? - /// - Remark: Generated from `#/components/schemas/MixedAnyOf/value3`. - public var value3: Components.Schemas.Pet? - /// - Remark: Generated from `#/components/schemas/MixedAnyOf/value4`. - public var value4: Swift.String? - /// Creates a new `MixedAnyOf`. - /// - /// - Parameters: - /// - value1: - /// - value2: - /// - value3: - /// - value4: - public init( - value1: Foundation.Date? = nil, - value2: Components.Schemas.PetKind? = nil, - value3: Components.Schemas.Pet? = nil, - value4: Swift.String? = nil - ) { - self.value1 = value1 - self.value2 = value2 - self.value3 = value3 - self.value4 = value4 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - value2 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - value3 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - value4 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - value1, - value2, - value3, - value4 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - value1, - value2, - value4 - ]) - try value3?.encode(to: encoder) - } - } - /// - Remark: Generated from `#/components/schemas/MixedOneOf`. - @frozen public enum MixedOneOf: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/MixedOneOf/case1`. - case case1(Foundation.Date) - /// - Remark: Generated from `#/components/schemas/MixedOneOf/case2`. - case PetKind(Components.Schemas.PetKind) - /// - Remark: Generated from `#/components/schemas/MixedOneOf/case3`. - case Pet(Components.Schemas.Pet) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self = .case1(try decoder.decodeFromSingleValueContainer()) - return - } catch { - errors.append(error) - } - do { - self = .PetKind(try decoder.decodeFromSingleValueContainer()) - return - } catch { - errors.append(error) - } - do { - self = .Pet(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - throw Swift.DecodingError.failedToDecodeOneOfSchema( - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - switch self { - case let .case1(value): - try encoder.encodeToSingleValueContainer(value) - case let .PetKind(value): - try encoder.encodeToSingleValueContainer(value) - case let .Pet(value): - try value.encode(to: encoder) - } - } - } - /// - Remark: Generated from `#/components/schemas/MixedAllOfPrimitive`. - public struct MixedAllOfPrimitive: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/MixedAllOfPrimitive/value1`. - public var value1: Foundation.Date - /// - Remark: Generated from `#/components/schemas/MixedAllOfPrimitive/value2`. - public var value2: Swift.String - /// Creates a new `MixedAllOfPrimitive`. - /// - /// - Parameters: - /// - value1: - /// - value2: - public init( - value1: Foundation.Date, - value2: Swift.String - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - value1 = try decoder.decodeFromSingleValueContainer() - value2 = try decoder.decodeFromSingleValueContainer() - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeToSingleValueContainer(value1) - } - } - /// Kind of pet - /// - /// - Remark: Generated from `#/components/schemas/PetKind`. - @frozen public enum PetKind: String, Codable, Hashable, Sendable, CaseIterable { - case cat = "cat" - case dog = "dog" - case ELEPHANT = "ELEPHANT" - case BIG_ELEPHANT_1 = "BIG_ELEPHANT_1" - case _dollar_nake = "$nake" - case _public = "public" - } - /// - Remark: Generated from `#/components/schemas/CreatePetRequest`. - public struct CreatePetRequest: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/CreatePetRequest/name`. - public var name: Swift.String - /// - Remark: Generated from `#/components/schemas/CreatePetRequest/kind`. - public var kind: Components.Schemas.PetKind? - /// - Remark: Generated from `#/components/schemas/CreatePetRequest/tag`. - public var tag: Swift.String? - /// - Remark: Generated from `#/components/schemas/CreatePetRequest/genome`. - public var genome: OpenAPIRuntime.Base64EncodedData? - /// Creates a new `CreatePetRequest`. - /// - /// - Parameters: - /// - name: - /// - kind: - /// - tag: - /// - genome: - public init( - name: Swift.String, - kind: Components.Schemas.PetKind? = nil, - tag: Swift.String? = nil, - genome: OpenAPIRuntime.Base64EncodedData? = nil - ) { - self.name = name - self.kind = kind - self.tag = tag - self.genome = genome - } - public enum CodingKeys: String, CodingKey { - case name - case kind - case tag - case genome - } - } - /// - Remark: Generated from `#/components/schemas/Pets`. - public typealias Pets = [Components.Schemas.Pet] - /// - Remark: Generated from `#/components/schemas/Error`. - public struct _Error: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/Error/code`. - public var code: Swift.Int32 - /// - Remark: Generated from `#/components/schemas/Error/me$sage`. - public var me_dollar_sage: Swift.String - /// Extra information about the error. - /// - /// - Remark: Generated from `#/components/schemas/Error/extraInfo`. - public var extraInfo: Components.Schemas.ExtraInfo? - /// Custom user-provided key-value pairs. - /// - /// - Remark: Generated from `#/components/schemas/Error/userData`. - public var userData: OpenAPIRuntime.OpenAPIObjectContainer? - /// Creates a new `_Error`. - /// - /// - Parameters: - /// - code: - /// - me_dollar_sage: - /// - extraInfo: Extra information about the error. - /// - userData: Custom user-provided key-value pairs. - public init( - code: Swift.Int32, - me_dollar_sage: Swift.String, - extraInfo: Components.Schemas.ExtraInfo? = nil, - userData: OpenAPIRuntime.OpenAPIObjectContainer? = nil - ) { - self.code = code - self.me_dollar_sage = me_dollar_sage - self.extraInfo = extraInfo - self.userData = userData - } - public enum CodingKeys: String, CodingKey { - case code - case me_dollar_sage = "me$sage" - case extraInfo - case userData - } - } - /// - Remark: Generated from `#/components/schemas/PetFeeding`. - public struct PetFeeding: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/PetFeeding/schedule`. - @frozen public enum schedulePayload: String, Codable, Hashable, Sendable, CaseIterable { - case hourly = "hourly" - case daily = "daily" - case weekly = "weekly" - } - /// - Remark: Generated from `#/components/schemas/PetFeeding/schedule`. - public var schedule: Components.Schemas.PetFeeding.schedulePayload? - /// Creates a new `PetFeeding`. - /// - /// - Parameters: - /// - schedule: - public init(schedule: Components.Schemas.PetFeeding.schedulePayload? = nil) { - self.schedule = schedule - } - public enum CodingKeys: String, CodingKey { - case schedule - } - } - /// - Remark: Generated from `#/components/schemas/DOB`. - public typealias DOB = Foundation.Date - /// - Remark: Generated from `#/components/schemas/ExtraInfo`. - public typealias ExtraInfo = Swift.String - /// - Remark: Generated from `#/components/schemas/NoAdditionalProperties`. - public struct NoAdditionalProperties: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/NoAdditionalProperties/foo`. - public var foo: Swift.String? - /// Creates a new `NoAdditionalProperties`. - /// - /// - Parameters: - /// - foo: - public init(foo: Swift.String? = nil) { - self.foo = foo - } - public enum CodingKeys: String, CodingKey { - case foo - } - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - foo = try container.decodeIfPresent( - Swift.String.self, - forKey: .foo - ) - try decoder.ensureNoAdditionalProperties(knownKeys: [ - "foo" - ]) - } - } - /// - Remark: Generated from `#/components/schemas/AnyAdditionalProperties`. - public struct AnyAdditionalProperties: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/AnyAdditionalProperties/foo`. - public var foo: Swift.String? - /// A container of undocumented properties. - public var additionalProperties: OpenAPIRuntime.OpenAPIObjectContainer - /// Creates a new `AnyAdditionalProperties`. - /// - /// - Parameters: - /// - foo: - /// - additionalProperties: A container of undocumented properties. - public init( - foo: Swift.String? = nil, - additionalProperties: OpenAPIRuntime.OpenAPIObjectContainer = .init() - ) { - self.foo = foo - self.additionalProperties = additionalProperties - } - public enum CodingKeys: String, CodingKey { - case foo - } - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - foo = try container.decodeIfPresent( - Swift.String.self, - forKey: .foo - ) - additionalProperties = try decoder.decodeAdditionalProperties(knownKeys: [ - "foo" - ]) - } - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent( - foo, - forKey: .foo - ) - try encoder.encodeAdditionalProperties(additionalProperties) - } - } - /// - Remark: Generated from `#/components/schemas/TypedAdditionalProperties`. - public struct TypedAdditionalProperties: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/TypedAdditionalProperties/foo`. - public var foo: Swift.String? - /// A container of undocumented properties. - public var additionalProperties: [String: Swift.Int] - /// Creates a new `TypedAdditionalProperties`. - /// - /// - Parameters: - /// - foo: - /// - additionalProperties: A container of undocumented properties. - public init( - foo: Swift.String? = nil, - additionalProperties: [String: Swift.Int] = .init() - ) { - self.foo = foo - self.additionalProperties = additionalProperties - } - public enum CodingKeys: String, CodingKey { - case foo - } - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - foo = try container.decodeIfPresent( - Swift.String.self, - forKey: .foo - ) - additionalProperties = try decoder.decodeAdditionalProperties(knownKeys: [ - "foo" - ]) - } - public func encode(to encoder: any Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent( - foo, - forKey: .foo - ) - try encoder.encodeAdditionalProperties(additionalProperties) - } - } - /// - Remark: Generated from `#/components/schemas/ObjectWithOptionalNullableArrayOfNullableItems`. - public struct ObjectWithOptionalNullableArrayOfNullableItems: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/ObjectWithOptionalNullableArrayOfNullableItems/foo`. - public var foo: [Swift.String?]? - /// Creates a new `ObjectWithOptionalNullableArrayOfNullableItems`. - /// - /// - Parameters: - /// - foo: - public init(foo: [Swift.String?]? = nil) { - self.foo = foo - } - public enum CodingKeys: String, CodingKey { - case foo - } - } - /// - Remark: Generated from `#/components/schemas/CodeError`. - public struct CodeError: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/CodeError/code`. - public var code: Swift.Int - /// Creates a new `CodeError`. - /// - /// - Parameters: - /// - code: - public init(code: Swift.Int) { - self.code = code - } - public enum CodingKeys: String, CodingKey { - case code - } - } - /// - Remark: Generated from `#/components/schemas/AllOfObjects`. - public struct AllOfObjects: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/AllOfObjects/value1`. - public struct Value1Payload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/AllOfObjects/value1/message`. - public var message: Swift.String - /// Creates a new `Value1Payload`. - /// - /// - Parameters: - /// - message: - public init(message: Swift.String) { - self.message = message - } - public enum CodingKeys: String, CodingKey { - case message - } - } - /// - Remark: Generated from `#/components/schemas/AllOfObjects/value1`. - public var value1: Components.Schemas.AllOfObjects.Value1Payload - /// - Remark: Generated from `#/components/schemas/AllOfObjects/value2`. - public var value2: Components.Schemas.CodeError - /// Creates a new `AllOfObjects`. - /// - /// - Parameters: - /// - value1: - /// - value2: - public init( - value1: Components.Schemas.AllOfObjects.Value1Payload, - value2: Components.Schemas.CodeError - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - value1 = try .init(from: decoder) - value2 = try .init(from: decoder) - } - public func encode(to encoder: any Encoder) throws { - try value1.encode(to: encoder) - try value2.encode(to: encoder) - } - } - /// - Remark: Generated from `#/components/schemas/AnyOfObjects`. - public struct AnyOfObjects: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/AnyOfObjects/value1`. - public struct Value1Payload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/AnyOfObjects/value1/message`. - public var message: Swift.String - /// Creates a new `Value1Payload`. - /// - /// - Parameters: - /// - message: - public init(message: Swift.String) { - self.message = message - } - public enum CodingKeys: String, CodingKey { - case message - } - } - /// - Remark: Generated from `#/components/schemas/AnyOfObjects/value1`. - public var value1: Components.Schemas.AnyOfObjects.Value1Payload? - /// - Remark: Generated from `#/components/schemas/AnyOfObjects/value2`. - public var value2: Components.Schemas.CodeError? - /// Creates a new `AnyOfObjects`. - /// - /// - Parameters: - /// - value1: - /// - value2: - public init( - value1: Components.Schemas.AnyOfObjects.Value1Payload? = nil, - value2: Components.Schemas.CodeError? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - value1 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - value1, - value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try value1?.encode(to: encoder) - try value2?.encode(to: encoder) - } - } - /// - Remark: Generated from `#/components/schemas/OneOfAny`. - @frozen public enum OneOfAny: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/OneOfAny/case1`. - case case1(Swift.String) - /// - Remark: Generated from `#/components/schemas/OneOfAny/case2`. - case case2(Swift.Int) - /// - Remark: Generated from `#/components/schemas/OneOfAny/case3`. - case CodeError(Components.Schemas.CodeError) - /// - Remark: Generated from `#/components/schemas/OneOfAny/case4`. - public struct Case4Payload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/OneOfAny/case4/message`. - public var message: Swift.String - /// Creates a new `Case4Payload`. - /// - /// - Parameters: - /// - message: - public init(message: Swift.String) { - self.message = message - } - public enum CodingKeys: String, CodingKey { - case message - } - } - /// - Remark: Generated from `#/components/schemas/OneOfAny/case4`. - case case4(Components.Schemas.OneOfAny.Case4Payload) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self = .case1(try decoder.decodeFromSingleValueContainer()) - return - } catch { - errors.append(error) - } - do { - self = .case2(try decoder.decodeFromSingleValueContainer()) - return - } catch { - errors.append(error) - } - do { - self = .CodeError(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { - self = .case4(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - throw Swift.DecodingError.failedToDecodeOneOfSchema( - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - switch self { - case let .case1(value): - try encoder.encodeToSingleValueContainer(value) - case let .case2(value): - try encoder.encodeToSingleValueContainer(value) - case let .CodeError(value): - try value.encode(to: encoder) - case let .case4(value): - try value.encode(to: encoder) - } - } - } - /// - Remark: Generated from `#/components/schemas/PetExercise`. - public struct PetExercise: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/PetExercise/kind`. - public var kind: Swift.String - /// Creates a new `PetExercise`. - /// - /// - Parameters: - /// - kind: - public init(kind: Swift.String) { - self.kind = kind - } - public enum CodingKeys: String, CodingKey { - case kind - } - } - /// - Remark: Generated from `#/components/schemas/Walk`. - public struct Walk: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/Walk/kind`. - public var kind: Swift.String - /// - Remark: Generated from `#/components/schemas/Walk/length`. - public var length: Swift.Int - /// Creates a new `Walk`. - /// - /// - Parameters: - /// - kind: - /// - length: - public init( - kind: Swift.String, - length: Swift.Int - ) { - self.kind = kind - self.length = length - } - public enum CodingKeys: String, CodingKey { - case kind - case length - } - } - /// - Remark: Generated from `#/components/schemas/MessagedExercise`. - public struct MessagedExercise: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/MessagedExercise/value1`. - public var value1: Components.Schemas.PetExercise - /// - Remark: Generated from `#/components/schemas/MessagedExercise/value2`. - public struct Value2Payload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/MessagedExercise/value2/message`. - public var message: Swift.String - /// Creates a new `Value2Payload`. - /// - /// - Parameters: - /// - message: - public init(message: Swift.String) { - self.message = message - } - public enum CodingKeys: String, CodingKey { - case message - } - } - /// - Remark: Generated from `#/components/schemas/MessagedExercise/value2`. - public var value2: Components.Schemas.MessagedExercise.Value2Payload - /// Creates a new `MessagedExercise`. - /// - /// - Parameters: - /// - value1: - /// - value2: - public init( - value1: Components.Schemas.PetExercise, - value2: Components.Schemas.MessagedExercise.Value2Payload - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - value1 = try .init(from: decoder) - value2 = try .init(from: decoder) - } - public func encode(to encoder: any Encoder) throws { - try value1.encode(to: encoder) - try value2.encode(to: encoder) - } - } - /// - Remark: Generated from `#/components/schemas/OneOfObjectsWithDiscriminator`. - @frozen public enum OneOfObjectsWithDiscriminator: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/OneOfObjectsWithDiscriminator/Walk`. - case Walk(Components.Schemas.Walk) - /// - Remark: Generated from `#/components/schemas/OneOfObjectsWithDiscriminator/MessagedExercise`. - case MessagedExercise(Components.Schemas.MessagedExercise) - public enum CodingKeys: String, CodingKey { - case kind - } - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let discriminator = try container.decode( - Swift.String.self, - forKey: .kind - ) - switch discriminator { - case "Walk", "#/components/schemas/Walk": - self = .Walk(try .init(from: decoder)) - case "MessagedExercise", "#/components/schemas/MessagedExercise": - self = .MessagedExercise(try .init(from: decoder)) - default: - throw Swift.DecodingError.unknownOneOfDiscriminator( - discriminatorKey: CodingKeys.kind, - discriminatorValue: discriminator, - codingPath: decoder.codingPath - ) - } - } - public func encode(to encoder: any Encoder) throws { - switch self { - case let .Walk(value): - try value.encode(to: encoder) - case let .MessagedExercise(value): - try value.encode(to: encoder) - } - } - } - /// - Remark: Generated from `#/components/schemas/PetStats`. - public struct PetStats: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/PetStats/count`. - public var count: Swift.Int - /// Creates a new `PetStats`. - /// - /// - Parameters: - /// - count: - public init(count: Swift.Int) { - self.count = count - } - public enum CodingKeys: String, CodingKey { - case count - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePet`. - public struct RecursivePet: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePet/name`. - public var name: Swift.String { - get { - storage.value.name - } - _modify { - yield &storage.value.name - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePet/parent`. - public var parent: Components.Schemas.RecursivePet? { - get { - storage.value.parent - } - _modify { - yield &storage.value.parent - } - } - /// Creates a new `RecursivePet`. - /// - /// - Parameters: - /// - name: - /// - parent: - public init( - name: Swift.String, - parent: Components.Schemas.RecursivePet? = nil - ) { - storage = .init(value: .init( - name: name, - parent: parent - )) - } - public enum CodingKeys: String, CodingKey { - case name - case parent - } - public init(from decoder: any Decoder) throws { - storage = try .init(from: decoder) - } - public func encode(to encoder: any Encoder) throws { - try storage.encode(to: encoder) - } - /// Internal reference storage to allow type recursion. - private var storage: OpenAPIRuntime.CopyOnWriteBox - private struct Storage: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePet/name`. - var name: Swift.String - /// - Remark: Generated from `#/components/schemas/RecursivePet/parent`. - var parent: Components.Schemas.RecursivePet? - init( - name: Swift.String, - parent: Components.Schemas.RecursivePet? = nil - ) { - self.name = name - self.parent = parent - } - typealias CodingKeys = Components.Schemas.RecursivePet.CodingKeys - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetNested`. - public struct RecursivePetNested: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetNested/name`. - public var name: Swift.String { - get { - storage.value.name - } - _modify { - yield &storage.value.name - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetNested/parent`. - public struct parentPayload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetNested/parent/nested`. - public var nested: Components.Schemas.RecursivePetNested - /// Creates a new `parentPayload`. - /// - /// - Parameters: - /// - nested: - public init(nested: Components.Schemas.RecursivePetNested) { - self.nested = nested - } - public enum CodingKeys: String, CodingKey { - case nested - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetNested/parent`. - public var parent: Components.Schemas.RecursivePetNested.parentPayload? { - get { - storage.value.parent - } - _modify { - yield &storage.value.parent - } - } - /// Creates a new `RecursivePetNested`. - /// - /// - Parameters: - /// - name: - /// - parent: - public init( - name: Swift.String, - parent: Components.Schemas.RecursivePetNested.parentPayload? = nil - ) { - storage = .init(value: .init( - name: name, - parent: parent - )) - } - public enum CodingKeys: String, CodingKey { - case name - case parent - } - public init(from decoder: any Decoder) throws { - storage = try .init(from: decoder) - } - public func encode(to encoder: any Encoder) throws { - try storage.encode(to: encoder) - } - /// Internal reference storage to allow type recursion. - private var storage: OpenAPIRuntime.CopyOnWriteBox - private struct Storage: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetNested/name`. - var name: Swift.String - /// - Remark: Generated from `#/components/schemas/RecursivePetNested/parent`. - struct parentPayload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetNested/parent/nested`. - public var nested: Components.Schemas.RecursivePetNested - /// Creates a new `parentPayload`. - /// - /// - Parameters: - /// - nested: - public init(nested: Components.Schemas.RecursivePetNested) { - self.nested = nested - } - public enum CodingKeys: String, CodingKey { - case nested - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetNested/parent`. - var parent: Components.Schemas.RecursivePetNested.parentPayload? - init( - name: Swift.String, - parent: Components.Schemas.RecursivePetNested.parentPayload? = nil - ) { - self.name = name - self.parent = parent - } - typealias CodingKeys = Components.Schemas.RecursivePetNested.CodingKeys - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst`. - public struct RecursivePetOneOfFirst: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value1`. - public var value1: Components.Schemas.RecursivePetOneOf { - get { - storage.value.value1 - } - _modify { - yield &storage.value.value1 - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value2`. - public struct Value2Payload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value2/type`. - public var _type: Swift.String - /// Creates a new `Value2Payload`. - /// - /// - Parameters: - /// - _type: - public init(_type: Swift.String) { - self._type = _type - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value2`. - public var value2: Components.Schemas.RecursivePetOneOfFirst.Value2Payload { - get { - storage.value.value2 - } - _modify { - yield &storage.value.value2 - } - } - /// Creates a new `RecursivePetOneOfFirst`. - /// - /// - Parameters: - /// - value1: - /// - value2: - public init( - value1: Components.Schemas.RecursivePetOneOf, - value2: Components.Schemas.RecursivePetOneOfFirst.Value2Payload - ) { - storage = .init(value: .init( - value1: value1, - value2: value2 - )) - } - public init(from decoder: any Decoder) throws { - storage = try .init(from: decoder) - } - public func encode(to encoder: any Encoder) throws { - try storage.encode(to: encoder) - } - /// Internal reference storage to allow type recursion. - private var storage: OpenAPIRuntime.CopyOnWriteBox - private struct Storage: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value1`. - var value1: Components.Schemas.RecursivePetOneOf - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value2`. - struct Value2Payload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value2/type`. - public var _type: Swift.String - /// Creates a new `Value2Payload`. - /// - /// - Parameters: - /// - _type: - public init(_type: Swift.String) { - self._type = _type - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfFirst/value2`. - var value2: Components.Schemas.RecursivePetOneOfFirst.Value2Payload - init( - value1: Components.Schemas.RecursivePetOneOf, - value2: Components.Schemas.RecursivePetOneOfFirst.Value2Payload - ) { - self.value1 = value1 - self.value2 = value2 - } - init(from decoder: any Decoder) throws { - value1 = try .init(from: decoder) - value2 = try .init(from: decoder) - } - func encode(to encoder: any Encoder) throws { - try value1.encode(to: encoder) - try value2.encode(to: encoder) - } - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfSecond`. - public struct RecursivePetOneOfSecond: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfSecond/value1`. - public var value1: Components.Schemas.Pet - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfSecond/value2`. - public struct Value2Payload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfSecond/value2/type`. - public var _type: Swift.String - /// Creates a new `Value2Payload`. - /// - /// - Parameters: - /// - _type: - public init(_type: Swift.String) { - self._type = _type - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOfSecond/value2`. - public var value2: Components.Schemas.RecursivePetOneOfSecond.Value2Payload - /// Creates a new `RecursivePetOneOfSecond`. - /// - /// - Parameters: - /// - value1: - /// - value2: - public init( - value1: Components.Schemas.Pet, - value2: Components.Schemas.RecursivePetOneOfSecond.Value2Payload - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - value1 = try .init(from: decoder) - value2 = try .init(from: decoder) - } - public func encode(to encoder: any Encoder) throws { - try value1.encode(to: encoder) - try value2.encode(to: encoder) - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOf`. - @frozen public enum RecursivePetOneOf: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOf/RecursivePetOneOfFirst`. - case RecursivePetOneOfFirst(Components.Schemas.RecursivePetOneOfFirst) - /// - Remark: Generated from `#/components/schemas/RecursivePetOneOf/RecursivePetOneOfSecond`. - case RecursivePetOneOfSecond(Components.Schemas.RecursivePetOneOfSecond) - public enum CodingKeys: String, CodingKey { - case _type = "type" - } - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let discriminator = try container.decode( - Swift.String.self, - forKey: ._type - ) - switch discriminator { - case "RecursivePetOneOfFirst", "#/components/schemas/RecursivePetOneOfFirst": - self = .RecursivePetOneOfFirst(try .init(from: decoder)) - case "RecursivePetOneOfSecond", "#/components/schemas/RecursivePetOneOfSecond": - self = .RecursivePetOneOfSecond(try .init(from: decoder)) - default: - throw Swift.DecodingError.unknownOneOfDiscriminator( - discriminatorKey: CodingKeys._type, - discriminatorValue: discriminator, - codingPath: decoder.codingPath - ) - } - } - public func encode(to encoder: any Encoder) throws { - switch self { - case let .RecursivePetOneOfFirst(value): - try value.encode(to: encoder) - case let .RecursivePetOneOfSecond(value): - try value.encode(to: encoder) - } - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetAnyOf`. - public struct RecursivePetAnyOf: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetAnyOf/value1`. - public var value1: Components.Schemas.RecursivePetAnyOf? { - get { - storage.value.value1 - } - _modify { - yield &storage.value.value1 - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetAnyOf/value2`. - public var value2: Swift.String? { - get { - storage.value.value2 - } - _modify { - yield &storage.value.value2 - } - } - /// Creates a new `RecursivePetAnyOf`. - /// - /// - Parameters: - /// - value1: - /// - value2: - public init( - value1: Components.Schemas.RecursivePetAnyOf? = nil, - value2: Swift.String? = nil - ) { - storage = .init(value: .init( - value1: value1, - value2: value2 - )) - } - public init(from decoder: any Decoder) throws { - storage = try .init(from: decoder) - } - public func encode(to encoder: any Encoder) throws { - try storage.encode(to: encoder) - } - /// Internal reference storage to allow type recursion. - private var storage: OpenAPIRuntime.CopyOnWriteBox - private struct Storage: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetAnyOf/value1`. - var value1: Components.Schemas.RecursivePetAnyOf? - /// - Remark: Generated from `#/components/schemas/RecursivePetAnyOf/value2`. - var value2: Swift.String? - init( - value1: Components.Schemas.RecursivePetAnyOf? = nil, - value2: Swift.String? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - value1 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - value2 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - value1, - value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - value2 - ]) - try value1?.encode(to: encoder) - } - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetAllOf`. - public struct RecursivePetAllOf: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetAllOf/value1`. - public struct Value1Payload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetAllOf/value1/parent`. - public var parent: Components.Schemas.RecursivePetAllOf? - /// Creates a new `Value1Payload`. - /// - /// - Parameters: - /// - parent: - public init(parent: Components.Schemas.RecursivePetAllOf? = nil) { - self.parent = parent - } - public enum CodingKeys: String, CodingKey { - case parent - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetAllOf/value1`. - public var value1: Components.Schemas.RecursivePetAllOf.Value1Payload { - get { - storage.value.value1 - } - _modify { - yield &storage.value.value1 - } - } - /// Creates a new `RecursivePetAllOf`. - /// - /// - Parameters: - /// - value1: - public init(value1: Components.Schemas.RecursivePetAllOf.Value1Payload) { - storage = .init(value: .init(value1: value1)) - } - public init(from decoder: any Decoder) throws { - storage = try .init(from: decoder) - } - public func encode(to encoder: any Encoder) throws { - try storage.encode(to: encoder) - } - /// Internal reference storage to allow type recursion. - private var storage: OpenAPIRuntime.CopyOnWriteBox - private struct Storage: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetAllOf/value1`. - struct Value1Payload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/RecursivePetAllOf/value1/parent`. - public var parent: Components.Schemas.RecursivePetAllOf? - /// Creates a new `Value1Payload`. - /// - /// - Parameters: - /// - parent: - public init(parent: Components.Schemas.RecursivePetAllOf? = nil) { - self.parent = parent - } - public enum CodingKeys: String, CodingKey { - case parent - } - } - /// - Remark: Generated from `#/components/schemas/RecursivePetAllOf/value1`. - var value1: Components.Schemas.RecursivePetAllOf.Value1Payload - init(value1: Components.Schemas.RecursivePetAllOf.Value1Payload) { - self.value1 = value1 - } - init(from decoder: any Decoder) throws { - value1 = try .init(from: decoder) - } - func encode(to encoder: any Encoder) throws { - try value1.encode(to: encoder) - } - } - } - } - /// Types generated from the `#/components/parameters` section of the OpenAPI document. - public enum Parameters { - /// Supply this parameter to filter pets born since the provided date. - /// - /// - Remark: Generated from `#/components/parameters/query.born-since`. - public typealias query_period_born_hyphen_since = Components.Schemas.DOB - /// The id of the pet to retrieve - /// - /// - Remark: Generated from `#/components/parameters/path.petId`. - public typealias path_period_petId = Swift.Int64 - } - /// Types generated from the `#/components/requestBodies` section of the OpenAPI document. - public enum RequestBodies { - /// - Remark: Generated from `#/components/requestBodies/UpdatePetRequest`. - @frozen public enum UpdatePetRequest: Sendable, Hashable { - /// - Remark: Generated from `#/components/requestBodies/UpdatePetRequest/json`. - public struct jsonPayload: Codable, Hashable, Sendable { - /// Pet name - /// - /// - Remark: Generated from `#/components/requestBodies/UpdatePetRequest/json/name`. - public var name: Swift.String? - /// - Remark: Generated from `#/components/requestBodies/UpdatePetRequest/json/kind`. - public var kind: Components.Schemas.PetKind? - /// - Remark: Generated from `#/components/requestBodies/UpdatePetRequest/json/tag`. - public var tag: Swift.String? - /// Creates a new `jsonPayload`. - /// - /// - Parameters: - /// - name: Pet name - /// - kind: - /// - tag: - public init( - name: Swift.String? = nil, - kind: Components.Schemas.PetKind? = nil, - tag: Swift.String? = nil - ) { - self.name = name - self.kind = kind - self.tag = tag - } - public enum CodingKeys: String, CodingKey { - case name - case kind - case tag - } - } - /// - Remark: Generated from `#/components/requestBodies/UpdatePetRequest/content/application\/json`. - case json(Components.RequestBodies.UpdatePetRequest.jsonPayload) - } - /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest`. - @frozen public enum MultipartUploadTypedRequest: Sendable, Hashable { - /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm`. - @frozen public enum multipartFormPayload: Sendable, Hashable { - /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/log`. - public struct logPayload: Sendable, Hashable { - /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/log/headers`. - public struct Headers: Sendable, Hashable { - /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/log/headers/x-log-type`. - @frozen public enum x_hyphen_log_hyphen_typePayload: String, Codable, Hashable, Sendable, CaseIterable { - case structured = "structured" - case unstructured = "unstructured" - } - /// The type of the log. - /// - /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/log/headers/x-log-type`. - public var x_hyphen_log_hyphen_type: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.logPayload.Headers.x_hyphen_log_hyphen_typePayload? - /// Creates a new `Headers`. - /// - /// - Parameters: - /// - x_hyphen_log_hyphen_type: The type of the log. - public init(x_hyphen_log_hyphen_type: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.logPayload.Headers.x_hyphen_log_hyphen_typePayload? = nil) { - self.x_hyphen_log_hyphen_type = x_hyphen_log_hyphen_type - } - } - /// Received HTTP response headers - public var headers: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.logPayload.Headers - public var body: OpenAPIRuntime.HTTPBody - /// Creates a new `logPayload`. - /// - /// - Parameters: - /// - headers: Received HTTP response headers - /// - body: - public init( - headers: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.logPayload.Headers = .init(), - body: OpenAPIRuntime.HTTPBody - ) { - self.headers = headers - self.body = body - } - } - case log(OpenAPIRuntime.MultipartPart) - /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/metadata`. - public struct metadataPayload: Sendable, Hashable { - /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/metadata/content/body`. - public struct bodyPayload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/metadata/content/body/createdAt`. - public var createdAt: Foundation.Date - /// Creates a new `bodyPayload`. - /// - /// - Parameters: - /// - createdAt: - public init(createdAt: Foundation.Date) { - self.createdAt = createdAt - } - public enum CodingKeys: String, CodingKey { - case createdAt - } - } - public var body: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.metadataPayload.bodyPayload - /// Creates a new `metadataPayload`. - /// - /// - Parameters: - /// - body: - public init(body: Components.RequestBodies.MultipartUploadTypedRequest.multipartFormPayload.metadataPayload.bodyPayload) { - self.body = body - } - } - case metadata(OpenAPIRuntime.MultipartPart) - /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/multipartForm/keyword`. - public struct keywordPayload: Sendable, Hashable { - public var body: OpenAPIRuntime.HTTPBody - /// Creates a new `keywordPayload`. - /// - /// - Parameters: - /// - body: - public init(body: OpenAPIRuntime.HTTPBody) { - self.body = body - } - } - case keyword(OpenAPIRuntime.MultipartPart) - case undocumented(OpenAPIRuntime.MultipartRawPart) - } - /// - Remark: Generated from `#/components/requestBodies/MultipartUploadTypedRequest/content/multipart\/form-data`. - case multipartForm(OpenAPIRuntime.MultipartBody) - } - } - /// Types generated from the `#/components/responses` section of the OpenAPI document. - public enum Responses { - public struct ErrorBadRequest: Sendable, Hashable { - /// - Remark: Generated from `#/components/responses/ErrorBadRequest/headers`. - public struct Headers: Sendable, Hashable { - /// A description here. - /// - /// - Remark: Generated from `#/components/responses/ErrorBadRequest/headers/X-Reason`. - public var X_hyphen_Reason: Swift.String? - /// Creates a new `Headers`. - /// - /// - Parameters: - /// - X_hyphen_Reason: A description here. - public init(X_hyphen_Reason: Swift.String? = nil) { - self.X_hyphen_Reason = X_hyphen_Reason - } - } - /// Received HTTP response headers - public var headers: Components.Responses.ErrorBadRequest.Headers - /// - Remark: Generated from `#/components/responses/ErrorBadRequest/content`. - @frozen public enum Body: Sendable, Hashable { - /// - Remark: Generated from `#/components/responses/ErrorBadRequest/content/json`. - public struct jsonPayload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/responses/ErrorBadRequest/content/json/code`. - public var code: Swift.Int - /// Creates a new `jsonPayload`. - /// - /// - Parameters: - /// - code: - public init(code: Swift.Int) { - self.code = code - } - public enum CodingKeys: String, CodingKey { - case code - } - } - /// - Remark: Generated from `#/components/responses/ErrorBadRequest/content/application\/json`. - case json(Components.Responses.ErrorBadRequest.Body.jsonPayload) - /// The associated value of the enum case if `self` is `.json`. - /// - /// - Throws: An error if `self` is not `.json`. - /// - SeeAlso: `.json`. - public var json: Components.Responses.ErrorBadRequest.Body.jsonPayload { - get throws { - switch self { - case let .json(body): - return body - } - } - } - } - /// Received HTTP response body - public var body: Components.Responses.ErrorBadRequest.Body - /// Creates a new `ErrorBadRequest`. - /// - /// - Parameters: - /// - headers: Received HTTP response headers - /// - body: Received HTTP response body - public init( - headers: Components.Responses.ErrorBadRequest.Headers = .init(), - body: Components.Responses.ErrorBadRequest.Body - ) { - self.headers = headers - self.body = body - } - } - public struct MultipartDownloadTypedResponse: Sendable, Hashable { - /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content`. - @frozen public enum Body: Sendable, Hashable { - /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm`. - @frozen public enum multipartFormPayload: Sendable, Hashable { - /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/log`. - public struct logPayload: Sendable, Hashable { - /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/log/headers`. - public struct Headers: Sendable, Hashable { - /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/log/headers/x-log-type`. - @frozen public enum x_hyphen_log_hyphen_typePayload: String, Codable, Hashable, Sendable, CaseIterable { - case structured = "structured" - case unstructured = "unstructured" - } - /// The type of the log. - /// - /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/log/headers/x-log-type`. - public var x_hyphen_log_hyphen_type: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.logPayload.Headers.x_hyphen_log_hyphen_typePayload? - /// Creates a new `Headers`. - /// - /// - Parameters: - /// - x_hyphen_log_hyphen_type: The type of the log. - public init(x_hyphen_log_hyphen_type: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.logPayload.Headers.x_hyphen_log_hyphen_typePayload? = nil) { - self.x_hyphen_log_hyphen_type = x_hyphen_log_hyphen_type - } - } - /// Received HTTP response headers - public var headers: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.logPayload.Headers - public var body: OpenAPIRuntime.HTTPBody - /// Creates a new `logPayload`. - /// - /// - Parameters: - /// - headers: Received HTTP response headers - /// - body: - public init( - headers: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.logPayload.Headers = .init(), - body: OpenAPIRuntime.HTTPBody - ) { - self.headers = headers - self.body = body - } - } - case log(OpenAPIRuntime.MultipartPart) - /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/metadata`. - public struct metadataPayload: Sendable, Hashable { - /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/metadata/content/body`. - public struct bodyPayload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/metadata/content/body/createdAt`. - public var createdAt: Foundation.Date - /// Creates a new `bodyPayload`. - /// - /// - Parameters: - /// - createdAt: - public init(createdAt: Foundation.Date) { - self.createdAt = createdAt - } - public enum CodingKeys: String, CodingKey { - case createdAt - } - } - public var body: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.metadataPayload.bodyPayload - /// Creates a new `metadataPayload`. - /// - /// - Parameters: - /// - body: - public init(body: Components.Responses.MultipartDownloadTypedResponse.Body.multipartFormPayload.metadataPayload.bodyPayload) { - self.body = body - } - } - case metadata(OpenAPIRuntime.MultipartPart) - /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipartForm/keyword`. - public struct keywordPayload: Sendable, Hashable { - public var body: OpenAPIRuntime.HTTPBody - /// Creates a new `keywordPayload`. - /// - /// - Parameters: - /// - body: - public init(body: OpenAPIRuntime.HTTPBody) { - self.body = body - } - } - case keyword(OpenAPIRuntime.MultipartPart) - case undocumented(OpenAPIRuntime.MultipartRawPart) - } - /// - Remark: Generated from `#/components/responses/MultipartDownloadTypedResponse/content/multipart\/form-data`. - case multipartForm(OpenAPIRuntime.MultipartBody) - /// The associated value of the enum case if `self` is `.multipartForm`. - /// - /// - Throws: An error if `self` is not `.multipartForm`. - /// - SeeAlso: `.multipartForm`. - public var multipartForm: OpenAPIRuntime.MultipartBody { - get throws { - switch self { - case let .multipartForm(body): - return body - } - } - } - } - /// Received HTTP response body - public var body: Components.Responses.MultipartDownloadTypedResponse.Body - /// Creates a new `MultipartDownloadTypedResponse`. - /// - /// - Parameters: - /// - body: Received HTTP response body - public init(body: Components.Responses.MultipartDownloadTypedResponse.Body) { - self.body = body - } - } - } - /// Types generated from the `#/components/headers` section of the OpenAPI document. - public enum Headers { - /// A description here. - /// - /// - Remark: Generated from `#/components/headers/TracingHeader`. - public typealias TracingHeader = Swift.String - } -} - -/// API operations, with input and output types, generated from `#/paths` in the OpenAPI document. -public enum Operations { - /// List all pets - /// - /// You can fetch - /// all the pets here - /// - /// - Remark: HTTP `GET /pets`. - /// - Remark: Generated from `#/paths//pets/get(listPets)`. - public enum listPets { - public static let id: Swift.String = "listPets" - public struct Input: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/GET/query`. - public struct Query: Sendable, Hashable { - /// How many items to return at one time (max 100) - /// - /// - Remark: Generated from `#/paths/pets/GET/query/limit`. - public var limit: Swift.Int32? - /// - Remark: Generated from `#/paths/pets/GET/query/habitat`. - @frozen public enum habitatPayload: String, Codable, Hashable, Sendable, CaseIterable { - case water = "water" - case land = "land" - case air = "air" - case _empty = "" - } - /// - Remark: Generated from `#/paths/pets/GET/query/habitat`. - public var habitat: Operations.listPets.Input.Query.habitatPayload? - /// - Remark: Generated from `#/paths/pets/GET/query/feedsPayload`. - @frozen public enum feedsPayloadPayload: String, Codable, Hashable, Sendable, CaseIterable { - case omnivore = "omnivore" - case carnivore = "carnivore" - case herbivore = "herbivore" - } - /// - Remark: Generated from `#/paths/pets/GET/query/feeds`. - public typealias feedsPayload = [Operations.listPets.Input.Query.feedsPayloadPayload] - /// - Remark: Generated from `#/paths/pets/GET/query/feeds`. - public var feeds: Operations.listPets.Input.Query.feedsPayload? - /// Supply this parameter to filter pets born since the provided date. - /// - /// - Remark: Generated from `#/paths/pets/GET/query/since`. - public var since: Components.Parameters.query_period_born_hyphen_since? - /// Creates a new `Query`. - /// - /// - Parameters: - /// - limit: How many items to return at one time (max 100) - /// - habitat: - /// - feeds: - /// - since: Supply this parameter to filter pets born since the provided date. - public init( - limit: Swift.Int32? = nil, - habitat: Operations.listPets.Input.Query.habitatPayload? = nil, - feeds: Operations.listPets.Input.Query.feedsPayload? = nil, - since: Components.Parameters.query_period_born_hyphen_since? = nil - ) { - self.limit = limit - self.habitat = habitat - self.feeds = feeds - self.since = since - } - } - public var query: Operations.listPets.Input.Query - /// - Remark: Generated from `#/paths/pets/GET/header`. - public struct Headers: Sendable, Hashable { - /// Request identifier - /// - /// - Remark: Generated from `#/paths/pets/GET/header/My-Request-UUID`. - public var My_hyphen_Request_hyphen_UUID: Swift.String? - public var accept: [OpenAPIRuntime.AcceptHeaderContentType] - /// Creates a new `Headers`. - /// - /// - Parameters: - /// - My_hyphen_Request_hyphen_UUID: Request identifier - /// - accept: - public init( - My_hyphen_Request_hyphen_UUID: Swift.String? = nil, - accept: [OpenAPIRuntime.AcceptHeaderContentType] = .defaultValues() - ) { - self.My_hyphen_Request_hyphen_UUID = My_hyphen_Request_hyphen_UUID - self.accept = accept - } - } - public var headers: Operations.listPets.Input.Headers - /// Creates a new `Input`. - /// - /// - Parameters: - /// - query: - /// - headers: - public init( - query: Operations.listPets.Input.Query = .init(), - headers: Operations.listPets.Input.Headers = .init() - ) { - self.query = query - self.headers = headers - } - } - @frozen public enum Output: Sendable, Hashable { - public struct Ok: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/GET/responses/200/headers`. - public struct Headers: Sendable, Hashable { - /// Response identifier - /// - /// - Remark: Generated from `#/paths/pets/GET/responses/200/headers/My-Response-UUID`. - public var My_hyphen_Response_hyphen_UUID: Swift.String - /// A description here. - /// - /// - Remark: Generated from `#/paths/pets/GET/responses/200/headers/My-Tracing-Header`. - public var My_hyphen_Tracing_hyphen_Header: Components.Headers.TracingHeader? - /// Creates a new `Headers`. - /// - /// - Parameters: - /// - My_hyphen_Response_hyphen_UUID: Response identifier - /// - My_hyphen_Tracing_hyphen_Header: A description here. - public init( - My_hyphen_Response_hyphen_UUID: Swift.String, - My_hyphen_Tracing_hyphen_Header: Components.Headers.TracingHeader? = nil - ) { - self.My_hyphen_Response_hyphen_UUID = My_hyphen_Response_hyphen_UUID - self.My_hyphen_Tracing_hyphen_Header = My_hyphen_Tracing_hyphen_Header - } - } - /// Received HTTP response headers - public var headers: Operations.listPets.Output.Ok.Headers - /// - Remark: Generated from `#/paths/pets/GET/responses/200/content`. - @frozen public enum Body: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/GET/responses/200/content/application\/json`. - case json(Components.Schemas.Pets) - /// The associated value of the enum case if `self` is `.json`. - /// - /// - Throws: An error if `self` is not `.json`. - /// - SeeAlso: `.json`. - public var json: Components.Schemas.Pets { - get throws { - switch self { - case let .json(body): - return body - } - } - } - } - /// Received HTTP response body - public var body: Operations.listPets.Output.Ok.Body - /// Creates a new `Ok`. - /// - /// - Parameters: - /// - headers: Received HTTP response headers - /// - body: Received HTTP response body - public init( - headers: Operations.listPets.Output.Ok.Headers, - body: Operations.listPets.Output.Ok.Body - ) { - self.headers = headers - self.body = body - } - } - /// A paged array of pets - /// - /// - Remark: Generated from `#/paths//pets/get(listPets)/responses/200`. - /// - /// HTTP response code: `200 ok`. - case ok(Operations.listPets.Output.Ok) - /// The associated value of the enum case if `self` is `.ok`. - /// - /// - Throws: An error if `self` is not `.ok`. - /// - SeeAlso: `.ok`. - public var ok: Operations.listPets.Output.Ok { - get throws { - switch self { - case let .ok(response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "ok", - response: self - ) - } - } - } - public struct Default: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/GET/responses/default/content`. - @frozen public enum Body: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/GET/responses/default/content/application\/json`. - case json(Components.Schemas._Error) - /// The associated value of the enum case if `self` is `.json`. - /// - /// - Throws: An error if `self` is not `.json`. - /// - SeeAlso: `.json`. - public var json: Components.Schemas._Error { - get throws { - switch self { - case let .json(body): - return body - } - } - } - } - /// Received HTTP response body - public var body: Operations.listPets.Output.Default.Body - /// Creates a new `Default`. - /// - /// - Parameters: - /// - body: Received HTTP response body - public init(body: Operations.listPets.Output.Default.Body) { - self.body = body - } - } - /// Unexpected error - /// - /// - Remark: Generated from `#/paths//pets/get(listPets)/responses/default`. - /// - /// HTTP response code: `default`. - case `default`(statusCode: Swift.Int, Operations.listPets.Output.Default) - /// The associated value of the enum case if `self` is `.`default``. - /// - /// - Throws: An error if `self` is not `.`default``. - /// - SeeAlso: `.`default``. - public var `default`: Operations.listPets.Output.Default { - get throws { - switch self { - case let .`default`(_, response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "default", - response: self - ) - } - } - } - } - @frozen public enum AcceptableContentType: AcceptableProtocol { - case json - case other(Swift.String) - public init?(rawValue: Swift.String) { - switch rawValue.lowercased() { - case "application/json": - self = .json - default: - self = .other(rawValue) - } - } - public var rawValue: Swift.String { - switch self { - case let .other(string): - return string - case .json: - return "application/json" - } - } - public static var allCases: [Self] { - [ - .json - ] - } - } - } - /// Create a pet - /// - /// - Remark: HTTP `POST /pets`. - /// - Remark: Generated from `#/paths//pets/post(createPet)`. - public enum createPet { - public static let id: Swift.String = "createPet" - public struct Input: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/POST/header`. - public struct Headers: Sendable, Hashable { - /// A description here. - /// - /// - Remark: Generated from `#/paths/pets/POST/header/X-Extra-Arguments`. - public var X_hyphen_Extra_hyphen_Arguments: Components.Schemas.CodeError? - public var accept: [OpenAPIRuntime.AcceptHeaderContentType] - /// Creates a new `Headers`. - /// - /// - Parameters: - /// - X_hyphen_Extra_hyphen_Arguments: A description here. - /// - accept: - public init( - X_hyphen_Extra_hyphen_Arguments: Components.Schemas.CodeError? = nil, - accept: [OpenAPIRuntime.AcceptHeaderContentType] = .defaultValues() - ) { - self.X_hyphen_Extra_hyphen_Arguments = X_hyphen_Extra_hyphen_Arguments - self.accept = accept - } - } - public var headers: Operations.createPet.Input.Headers - /// - Remark: Generated from `#/paths/pets/POST/requestBody`. - @frozen public enum Body: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/POST/requestBody/content/application\/json`. - case json(Components.Schemas.CreatePetRequest) - } - public var body: Operations.createPet.Input.Body - /// Creates a new `Input`. - /// - /// - Parameters: - /// - headers: - /// - body: - public init( - headers: Operations.createPet.Input.Headers = .init(), - body: Operations.createPet.Input.Body - ) { - self.headers = headers - self.body = body - } - } - @frozen public enum Output: Sendable, Hashable { - public struct Created: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/POST/responses/201/headers`. - public struct Headers: Sendable, Hashable { - /// A description here. - /// - /// - Remark: Generated from `#/paths/pets/POST/responses/201/headers/X-Extra-Arguments`. - public var X_hyphen_Extra_hyphen_Arguments: Components.Schemas.CodeError? - /// Creates a new `Headers`. - /// - /// - Parameters: - /// - X_hyphen_Extra_hyphen_Arguments: A description here. - public init(X_hyphen_Extra_hyphen_Arguments: Components.Schemas.CodeError? = nil) { - self.X_hyphen_Extra_hyphen_Arguments = X_hyphen_Extra_hyphen_Arguments - } - } - /// Received HTTP response headers - public var headers: Operations.createPet.Output.Created.Headers - /// - Remark: Generated from `#/paths/pets/POST/responses/201/content`. - @frozen public enum Body: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/POST/responses/201/content/application\/json`. - case json(Components.Schemas.Pet) - /// The associated value of the enum case if `self` is `.json`. - /// - /// - Throws: An error if `self` is not `.json`. - /// - SeeAlso: `.json`. - public var json: Components.Schemas.Pet { - get throws { - switch self { - case let .json(body): - return body - } - } - } - } - /// Received HTTP response body - public var body: Operations.createPet.Output.Created.Body - /// Creates a new `Created`. - /// - /// - Parameters: - /// - headers: Received HTTP response headers - /// - body: Received HTTP response body - public init( - headers: Operations.createPet.Output.Created.Headers = .init(), - body: Operations.createPet.Output.Created.Body - ) { - self.headers = headers - self.body = body - } - } - /// Successfully created pet - /// - /// - Remark: Generated from `#/paths//pets/post(createPet)/responses/201`. - /// - /// HTTP response code: `201 created`. - case created(Operations.createPet.Output.Created) - /// The associated value of the enum case if `self` is `.created`. - /// - /// - Throws: An error if `self` is not `.created`. - /// - SeeAlso: `.created`. - public var created: Operations.createPet.Output.Created { - get throws { - switch self { - case let .created(response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "created", - response: self - ) - } - } - } - /// Bad request - /// - /// - Remark: Generated from `#/paths//pets/post(createPet)/responses/4XX`. - /// - /// HTTP response code: `400...499 clientError`. - case clientError(statusCode: Swift.Int, Components.Responses.ErrorBadRequest) - /// The associated value of the enum case if `self` is `.clientError`. - /// - /// - Throws: An error if `self` is not `.clientError`. - /// - SeeAlso: `.clientError`. - public var clientError: Components.Responses.ErrorBadRequest { - get throws { - switch self { - case let .clientError(_, response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "clientError", - response: self - ) - } - } - } - /// Undocumented response. - /// - /// A response with a code that is not documented in the OpenAPI document. - case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) - } - @frozen public enum AcceptableContentType: AcceptableProtocol { - case json - case other(Swift.String) - public init?(rawValue: Swift.String) { - switch rawValue.lowercased() { - case "application/json": - self = .json - default: - self = .other(rawValue) - } - } - public var rawValue: Swift.String { - switch self { - case let .other(string): - return string - case .json: - return "application/json" - } - } - public static var allCases: [Self] { - [ - .json - ] - } - } - } - /// Create a pet using a url form - /// - /// - Remark: HTTP `POST /pets/create`. - /// - Remark: Generated from `#/paths//pets/create/post(createPetWithForm)`. - public enum createPetWithForm { - public static let id: Swift.String = "createPetWithForm" - public struct Input: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/create/POST/requestBody`. - @frozen public enum Body: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/create/POST/requestBody/content/application\/x-www-form-urlencoded`. - case urlEncodedForm(Components.Schemas.CreatePetRequest) - } - public var body: Operations.createPetWithForm.Input.Body - /// Creates a new `Input`. - /// - /// - Parameters: - /// - body: - public init(body: Operations.createPetWithForm.Input.Body) { - self.body = body - } - } - @frozen public enum Output: Sendable, Hashable { - public struct NoContent: Sendable, Hashable { - /// Creates a new `NoContent`. - public init() {} - } - /// Successfully created pet using a url form - /// - /// - Remark: Generated from `#/paths//pets/create/post(createPetWithForm)/responses/204`. - /// - /// HTTP response code: `204 noContent`. - case noContent(Operations.createPetWithForm.Output.NoContent) - /// The associated value of the enum case if `self` is `.noContent`. - /// - /// - Throws: An error if `self` is not `.noContent`. - /// - SeeAlso: `.noContent`. - public var noContent: Operations.createPetWithForm.Output.NoContent { - get throws { - switch self { - case let .noContent(response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "noContent", - response: self - ) - } - } - } - /// Undocumented response. - /// - /// A response with a code that is not documented in the OpenAPI document. - case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) - } - } - /// - Remark: HTTP `GET /pets/stats`. - /// - Remark: Generated from `#/paths//pets/stats/get(getStats)`. - public enum getStats { - public static let id: Swift.String = "getStats" - public struct Input: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/stats/GET/header`. - public struct Headers: Sendable, Hashable { - public var accept: [OpenAPIRuntime.AcceptHeaderContentType] - /// Creates a new `Headers`. - /// - /// - Parameters: - /// - accept: - public init(accept: [OpenAPIRuntime.AcceptHeaderContentType] = .defaultValues()) { - self.accept = accept - } - } - public var headers: Operations.getStats.Input.Headers - /// Creates a new `Input`. - /// - /// - Parameters: - /// - headers: - public init(headers: Operations.getStats.Input.Headers = .init()) { - self.headers = headers - } - } - @frozen public enum Output: Sendable, Hashable { - public struct Ok: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/stats/GET/responses/200/content`. - @frozen public enum Body: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/stats/GET/responses/200/content/application\/json`. - case json(Components.Schemas.PetStats) - /// The associated value of the enum case if `self` is `.json`. - /// - /// - Throws: An error if `self` is not `.json`. - /// - SeeAlso: `.json`. - public var json: Components.Schemas.PetStats { - get throws { - switch self { - case let .json(body): - return body - default: - try throwUnexpectedResponseBody( - expectedContent: "application/json", - body: self - ) - } - } - } - /// - Remark: Generated from `#/paths/pets/stats/GET/responses/200/content/text\/plain`. - case plainText(OpenAPIRuntime.HTTPBody) - /// The associated value of the enum case if `self` is `.plainText`. - /// - /// - Throws: An error if `self` is not `.plainText`. - /// - SeeAlso: `.plainText`. - public var plainText: OpenAPIRuntime.HTTPBody { - get throws { - switch self { - case let .plainText(body): - return body - default: - try throwUnexpectedResponseBody( - expectedContent: "text/plain", - body: self - ) - } - } - } - /// - Remark: Generated from `#/paths/pets/stats/GET/responses/200/content/application\/octet-stream`. - case binary(OpenAPIRuntime.HTTPBody) - /// The associated value of the enum case if `self` is `.binary`. - /// - /// - Throws: An error if `self` is not `.binary`. - /// - SeeAlso: `.binary`. - public var binary: OpenAPIRuntime.HTTPBody { - get throws { - switch self { - case let .binary(body): - return body - default: - try throwUnexpectedResponseBody( - expectedContent: "application/octet-stream", - body: self - ) - } - } - } - } - /// Received HTTP response body - public var body: Operations.getStats.Output.Ok.Body - /// Creates a new `Ok`. - /// - /// - Parameters: - /// - body: Received HTTP response body - public init(body: Operations.getStats.Output.Ok.Body) { - self.body = body - } - } - /// A successful response. - /// - /// - Remark: Generated from `#/paths//pets/stats/get(getStats)/responses/200`. - /// - /// HTTP response code: `200 ok`. - case ok(Operations.getStats.Output.Ok) - /// The associated value of the enum case if `self` is `.ok`. - /// - /// - Throws: An error if `self` is not `.ok`. - /// - SeeAlso: `.ok`. - public var ok: Operations.getStats.Output.Ok { - get throws { - switch self { - case let .ok(response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "ok", - response: self - ) - } - } - } - /// Undocumented response. - /// - /// A response with a code that is not documented in the OpenAPI document. - case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) - } - @frozen public enum AcceptableContentType: AcceptableProtocol { - case json - case plainText - case binary - case other(Swift.String) - public init?(rawValue: Swift.String) { - switch rawValue.lowercased() { - case "application/json": - self = .json - case "text/plain": - self = .plainText - case "application/octet-stream": - self = .binary - default: - self = .other(rawValue) - } - } - public var rawValue: Swift.String { - switch self { - case let .other(string): - return string - case .json: - return "application/json" - case .plainText: - return "text/plain" - case .binary: - return "application/octet-stream" - } - } - public static var allCases: [Self] { - [ - .json, - .plainText, - .binary - ] - } - } - } - /// - Remark: HTTP `POST /pets/stats`. - /// - Remark: Generated from `#/paths//pets/stats/post(postStats)`. - public enum postStats { - public static let id: Swift.String = "postStats" - public struct Input: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/stats/POST/requestBody`. - @frozen public enum Body: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/stats/POST/requestBody/content/application\/json`. - case json(Components.Schemas.PetStats) - /// - Remark: Generated from `#/paths/pets/stats/POST/requestBody/content/text\/plain`. - case plainText(OpenAPIRuntime.HTTPBody) - /// - Remark: Generated from `#/paths/pets/stats/POST/requestBody/content/application\/octet-stream`. - case binary(OpenAPIRuntime.HTTPBody) - } - public var body: Operations.postStats.Input.Body - /// Creates a new `Input`. - /// - /// - Parameters: - /// - body: - public init(body: Operations.postStats.Input.Body) { - self.body = body - } - } - @frozen public enum Output: Sendable, Hashable { - public struct Accepted: Sendable, Hashable { - /// Creates a new `Accepted`. - public init() {} - } - /// Accepted data. - /// - /// - Remark: Generated from `#/paths//pets/stats/post(postStats)/responses/202`. - /// - /// HTTP response code: `202 accepted`. - case accepted(Operations.postStats.Output.Accepted) - /// The associated value of the enum case if `self` is `.accepted`. - /// - /// - Throws: An error if `self` is not `.accepted`. - /// - SeeAlso: `.accepted`. - public var accepted: Operations.postStats.Output.Accepted { - get throws { - switch self { - case let .accepted(response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "accepted", - response: self - ) - } - } - } - /// Undocumented response. - /// - /// A response with a code that is not documented in the OpenAPI document. - case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) - } - } - /// - Remark: HTTP `POST /probe/`. - /// - Remark: Generated from `#/paths//probe//post(probe)`. - public enum probe { - public static let id: Swift.String = "probe" - public struct Input: Sendable, Hashable { - /// Creates a new `Input`. - public init() {} - } - @frozen public enum Output: Sendable, Hashable { - public struct NoContent: Sendable, Hashable { - /// Creates a new `NoContent`. - public init() {} - } - /// Ack - /// - /// - Remark: Generated from `#/paths//probe//post(probe)/responses/204`. - /// - /// HTTP response code: `204 noContent`. - case noContent(Operations.probe.Output.NoContent) - /// The associated value of the enum case if `self` is `.noContent`. - /// - /// - Throws: An error if `self` is not `.noContent`. - /// - SeeAlso: `.noContent`. - public var noContent: Operations.probe.Output.NoContent { - get throws { - switch self { - case let .noContent(response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "noContent", - response: self - ) - } - } - } - /// Undocumented response. - /// - /// A response with a code that is not documented in the OpenAPI document. - case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) - } - } - /// Update just a specific property of an existing pet. Nothing is updated if no request body is provided. - /// - /// - Remark: HTTP `PATCH /pets/{petId}`. - /// - Remark: Generated from `#/paths//pets/{petId}/patch(updatePet)`. - public enum updatePet { - public static let id: Swift.String = "updatePet" - public struct Input: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/{petId}/PATCH/path`. - public struct Path: Sendable, Hashable { - /// Id of the pet - /// - /// - Remark: Generated from `#/paths/pets/{petId}/PATCH/path/petId`. - public var petId: Swift.Int64 - /// Creates a new `Path`. - /// - /// - Parameters: - /// - petId: Id of the pet - public init(petId: Swift.Int64) { - self.petId = petId - } - } - public var path: Operations.updatePet.Input.Path - /// - Remark: Generated from `#/paths/pets/{petId}/PATCH/header`. - public struct Headers: Sendable, Hashable { - public var accept: [OpenAPIRuntime.AcceptHeaderContentType] - /// Creates a new `Headers`. - /// - /// - Parameters: - /// - accept: - public init(accept: [OpenAPIRuntime.AcceptHeaderContentType] = .defaultValues()) { - self.accept = accept - } - } - public var headers: Operations.updatePet.Input.Headers - public var body: Components.RequestBodies.UpdatePetRequest? - /// Creates a new `Input`. - /// - /// - Parameters: - /// - path: - /// - headers: - /// - body: - public init( - path: Operations.updatePet.Input.Path, - headers: Operations.updatePet.Input.Headers = .init(), - body: Components.RequestBodies.UpdatePetRequest? = nil - ) { - self.path = path - self.headers = headers - self.body = body - } - } - @frozen public enum Output: Sendable, Hashable { - public struct NoContent: Sendable, Hashable { - /// Creates a new `NoContent`. - public init() {} - } - /// Successfully updated - /// - /// - Remark: Generated from `#/paths//pets/{petId}/patch(updatePet)/responses/204`. - /// - /// HTTP response code: `204 noContent`. - case noContent(Operations.updatePet.Output.NoContent) - /// The associated value of the enum case if `self` is `.noContent`. - /// - /// - Throws: An error if `self` is not `.noContent`. - /// - SeeAlso: `.noContent`. - public var noContent: Operations.updatePet.Output.NoContent { - get throws { - switch self { - case let .noContent(response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "noContent", - response: self - ) - } - } - } - public struct BadRequest: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/{petId}/PATCH/responses/400/content`. - @frozen public enum Body: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/{petId}/PATCH/responses/400/content/json`. - public struct jsonPayload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/paths/pets/{petId}/PATCH/responses/400/content/json/message`. - public var message: Swift.String - /// Creates a new `jsonPayload`. - /// - /// - Parameters: - /// - message: - public init(message: Swift.String) { - self.message = message - } - public enum CodingKeys: String, CodingKey { - case message - } - } - /// - Remark: Generated from `#/paths/pets/{petId}/PATCH/responses/400/content/application\/json`. - case json(Operations.updatePet.Output.BadRequest.Body.jsonPayload) - /// The associated value of the enum case if `self` is `.json`. - /// - /// - Throws: An error if `self` is not `.json`. - /// - SeeAlso: `.json`. - public var json: Operations.updatePet.Output.BadRequest.Body.jsonPayload { - get throws { - switch self { - case let .json(body): - return body - } - } - } - } - /// Received HTTP response body - public var body: Operations.updatePet.Output.BadRequest.Body - /// Creates a new `BadRequest`. - /// - /// - Parameters: - /// - body: Received HTTP response body - public init(body: Operations.updatePet.Output.BadRequest.Body) { - self.body = body - } - } - /// Update input error - /// - /// - Remark: Generated from `#/paths//pets/{petId}/patch(updatePet)/responses/400`. - /// - /// HTTP response code: `400 badRequest`. - case badRequest(Operations.updatePet.Output.BadRequest) - /// The associated value of the enum case if `self` is `.badRequest`. - /// - /// - Throws: An error if `self` is not `.badRequest`. - /// - SeeAlso: `.badRequest`. - public var badRequest: Operations.updatePet.Output.BadRequest { - get throws { - switch self { - case let .badRequest(response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "badRequest", - response: self - ) - } - } - } - /// Undocumented response. - /// - /// A response with a code that is not documented in the OpenAPI document. - case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) - } - @frozen public enum AcceptableContentType: AcceptableProtocol { - case json - case other(Swift.String) - public init?(rawValue: Swift.String) { - switch rawValue.lowercased() { - case "application/json": - self = .json - default: - self = .other(rawValue) - } - } - public var rawValue: Swift.String { - switch self { - case let .other(string): - return string - case .json: - return "application/json" - } - } - public static var allCases: [Self] { - [ - .json - ] - } - } - } - /// Upload an avatar - /// - /// - Remark: HTTP `PUT /pets/{petId}/avatar`. - /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)`. - public enum uploadAvatarForPet { - public static let id: Swift.String = "uploadAvatarForPet" - public struct Input: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/path`. - public struct Path: Sendable, Hashable { - /// The id of the pet to retrieve - /// - /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/path/petId`. - public var petId: Components.Parameters.path_period_petId - /// Creates a new `Path`. - /// - /// - Parameters: - /// - petId: The id of the pet to retrieve - public init(petId: Components.Parameters.path_period_petId) { - self.petId = petId - } - } - public var path: Operations.uploadAvatarForPet.Input.Path - /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/header`. - public struct Headers: Sendable, Hashable { - public var accept: [OpenAPIRuntime.AcceptHeaderContentType] - /// Creates a new `Headers`. - /// - /// - Parameters: - /// - accept: - public init(accept: [OpenAPIRuntime.AcceptHeaderContentType] = .defaultValues()) { - self.accept = accept - } - } - public var headers: Operations.uploadAvatarForPet.Input.Headers - /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/requestBody`. - @frozen public enum Body: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/requestBody/content/application\/octet-stream`. - case binary(OpenAPIRuntime.HTTPBody) - } - public var body: Operations.uploadAvatarForPet.Input.Body - /// Creates a new `Input`. - /// - /// - Parameters: - /// - path: - /// - headers: - /// - body: - public init( - path: Operations.uploadAvatarForPet.Input.Path, - headers: Operations.uploadAvatarForPet.Input.Headers = .init(), - body: Operations.uploadAvatarForPet.Input.Body - ) { - self.path = path - self.headers = headers - self.body = body - } - } - @frozen public enum Output: Sendable, Hashable { - public struct Ok: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/responses/200/content`. - @frozen public enum Body: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/responses/200/content/application\/octet-stream`. - case binary(OpenAPIRuntime.HTTPBody) - /// The associated value of the enum case if `self` is `.binary`. - /// - /// - Throws: An error if `self` is not `.binary`. - /// - SeeAlso: `.binary`. - public var binary: OpenAPIRuntime.HTTPBody { - get throws { - switch self { - case let .binary(body): - return body - } - } - } - } - /// Received HTTP response body - public var body: Operations.uploadAvatarForPet.Output.Ok.Body - /// Creates a new `Ok`. - /// - /// - Parameters: - /// - body: Received HTTP response body - public init(body: Operations.uploadAvatarForPet.Output.Ok.Body) { - self.body = body - } - } - /// Echoes avatar back - /// - /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)/responses/200`. - /// - /// HTTP response code: `200 ok`. - case ok(Operations.uploadAvatarForPet.Output.Ok) - /// The associated value of the enum case if `self` is `.ok`. - /// - /// - Throws: An error if `self` is not `.ok`. - /// - SeeAlso: `.ok`. - public var ok: Operations.uploadAvatarForPet.Output.Ok { - get throws { - switch self { - case let .ok(response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "ok", - response: self - ) - } - } - } - public struct PreconditionFailed: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/responses/412/content`. - @frozen public enum Body: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/responses/412/content/application\/json`. - case json(Swift.String) - /// The associated value of the enum case if `self` is `.json`. - /// - /// - Throws: An error if `self` is not `.json`. - /// - SeeAlso: `.json`. - public var json: Swift.String { - get throws { - switch self { - case let .json(body): - return body - } - } - } - } - /// Received HTTP response body - public var body: Operations.uploadAvatarForPet.Output.PreconditionFailed.Body - /// Creates a new `PreconditionFailed`. - /// - /// - Parameters: - /// - body: Received HTTP response body - public init(body: Operations.uploadAvatarForPet.Output.PreconditionFailed.Body) { - self.body = body - } - } - /// Avatar is not acceptable - /// - /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)/responses/412`. - /// - /// HTTP response code: `412 preconditionFailed`. - case preconditionFailed(Operations.uploadAvatarForPet.Output.PreconditionFailed) - /// The associated value of the enum case if `self` is `.preconditionFailed`. - /// - /// - Throws: An error if `self` is not `.preconditionFailed`. - /// - SeeAlso: `.preconditionFailed`. - public var preconditionFailed: Operations.uploadAvatarForPet.Output.PreconditionFailed { - get throws { - switch self { - case let .preconditionFailed(response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "preconditionFailed", - response: self - ) - } - } - } - public struct InternalServerError: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/responses/500/content`. - @frozen public enum Body: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/{petId}/avatar/PUT/responses/500/content/text\/plain`. - case plainText(OpenAPIRuntime.HTTPBody) - /// The associated value of the enum case if `self` is `.plainText`. - /// - /// - Throws: An error if `self` is not `.plainText`. - /// - SeeAlso: `.plainText`. - public var plainText: OpenAPIRuntime.HTTPBody { - get throws { - switch self { - case let .plainText(body): - return body - } - } - } - } - /// Received HTTP response body - public var body: Operations.uploadAvatarForPet.Output.InternalServerError.Body - /// Creates a new `InternalServerError`. - /// - /// - Parameters: - /// - body: Received HTTP response body - public init(body: Operations.uploadAvatarForPet.Output.InternalServerError.Body) { - self.body = body - } - } - /// Server error - /// - /// - Remark: Generated from `#/paths//pets/{petId}/avatar/put(uploadAvatarForPet)/responses/500`. - /// - /// HTTP response code: `500 internalServerError`. - case internalServerError(Operations.uploadAvatarForPet.Output.InternalServerError) - /// The associated value of the enum case if `self` is `.internalServerError`. - /// - /// - Throws: An error if `self` is not `.internalServerError`. - /// - SeeAlso: `.internalServerError`. - public var internalServerError: Operations.uploadAvatarForPet.Output.InternalServerError { - get throws { - switch self { - case let .internalServerError(response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "internalServerError", - response: self - ) - } - } - } - /// Undocumented response. - /// - /// A response with a code that is not documented in the OpenAPI document. - case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) - } - @frozen public enum AcceptableContentType: AcceptableProtocol { - case binary - case json - case plainText - case other(Swift.String) - public init?(rawValue: Swift.String) { - switch rawValue.lowercased() { - case "application/octet-stream": - self = .binary - case "application/json": - self = .json - case "text/plain": - self = .plainText - default: - self = .other(rawValue) - } - } - public var rawValue: Swift.String { - switch self { - case let .other(string): - return string - case .binary: - return "application/octet-stream" - case .json: - return "application/json" - case .plainText: - return "text/plain" - } - } - public static var allCases: [Self] { - [ - .binary, - .json, - .plainText - ] - } - } - } - /// - Remark: HTTP `GET /pets/multipart-typed`. - /// - Remark: Generated from `#/paths//pets/multipart-typed/get(multipartDownloadTyped)`. - public enum multipartDownloadTyped { - public static let id: Swift.String = "multipartDownloadTyped" - public struct Input: Sendable, Hashable { - /// - Remark: Generated from `#/paths/pets/multipart-typed/GET/header`. - public struct Headers: Sendable, Hashable { - public var accept: [OpenAPIRuntime.AcceptHeaderContentType] - /// Creates a new `Headers`. - /// - /// - Parameters: - /// - accept: - public init(accept: [OpenAPIRuntime.AcceptHeaderContentType] = .defaultValues()) { - self.accept = accept - } - } - public var headers: Operations.multipartDownloadTyped.Input.Headers - /// Creates a new `Input`. - /// - /// - Parameters: - /// - headers: - public init(headers: Operations.multipartDownloadTyped.Input.Headers = .init()) { - self.headers = headers - } - } - @frozen public enum Output: Sendable, Hashable { - /// A typed multipart response. - /// - /// - Remark: Generated from `#/paths//pets/multipart-typed/get(multipartDownloadTyped)/responses/200`. - /// - /// HTTP response code: `200 ok`. - case ok(Components.Responses.MultipartDownloadTypedResponse) - /// The associated value of the enum case if `self` is `.ok`. - /// - /// - Throws: An error if `self` is not `.ok`. - /// - SeeAlso: `.ok`. - public var ok: Components.Responses.MultipartDownloadTypedResponse { - get throws { - switch self { - case let .ok(response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "ok", - response: self - ) - } - } - } - /// Undocumented response. - /// - /// A response with a code that is not documented in the OpenAPI document. - case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) - } - @frozen public enum AcceptableContentType: AcceptableProtocol { - case multipartForm - case other(Swift.String) - public init?(rawValue: Swift.String) { - switch rawValue.lowercased() { - case "multipart/form-data": - self = .multipartForm - default: - self = .other(rawValue) - } - } - public var rawValue: Swift.String { - switch self { - case let .other(string): - return string - case .multipartForm: - return "multipart/form-data" - } - } - public static var allCases: [Self] { - [ - .multipartForm - ] - } - } - } - /// - Remark: HTTP `POST /pets/multipart-typed`. - /// - Remark: Generated from `#/paths//pets/multipart-typed/post(multipartUploadTyped)`. - public enum multipartUploadTyped { - public static let id: Swift.String = "multipartUploadTyped" - public struct Input: Sendable, Hashable { - public var body: Components.RequestBodies.MultipartUploadTypedRequest - /// Creates a new `Input`. - /// - /// - Parameters: - /// - body: - public init(body: Components.RequestBodies.MultipartUploadTypedRequest) { - self.body = body - } - } - @frozen public enum Output: Sendable, Hashable { - public struct Accepted: Sendable, Hashable { - /// Creates a new `Accepted`. - public init() {} - } - /// Successfully accepted the data. - /// - /// - Remark: Generated from `#/paths//pets/multipart-typed/post(multipartUploadTyped)/responses/202`. - /// - /// HTTP response code: `202 accepted`. - case accepted(Operations.multipartUploadTyped.Output.Accepted) - /// The associated value of the enum case if `self` is `.accepted`. - /// - /// - Throws: An error if `self` is not `.accepted`. - /// - SeeAlso: `.accepted`. - public var accepted: Operations.multipartUploadTyped.Output.Accepted { - get throws { - switch self { - case let .accepted(response): - return response - default: - try throwUnexpectedResponseStatus( - expectedStatus: "accepted", - response: self - ) - } - } - } - /// Undocumented response. - /// - /// A response with a code that is not documented in the OpenAPI document. - case undocumented(statusCode: Swift.Int, OpenAPIRuntime.UndocumentedPayload) - } - } -} From ad29a411ca9e0d2769b5517a015673b3b4fb427c Mon Sep 17 00:00:00 2001 From: theoriginalbit <1377564+theoriginalbit@users.noreply.github.com> Date: Thu, 19 Sep 2024 21:44:33 +1000 Subject: [PATCH 05/13] Introduce snippet-based reference tests for server variable translation --- .../TypesTranslator/translateServers.swift | 1 - .../SnippetBasedReferenceTests.swift | 406 ++++++++++++++++++ 2 files changed, 406 insertions(+), 1 deletion(-) diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift index aff1be9d..eaa7efd4 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift @@ -78,7 +78,6 @@ extension TypesFileTranslator { var serverDecls: [Declaration] = [] - for (index, decl) in servers.enumerated() { let serverDecl = translateServer(index: index, server: decl, variablesNamespace: &variablesNamespace) serverDecls.append(serverDecl) diff --git a/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift b/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift index 0196c5ee..7ed2ae4d 100644 --- a/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift +++ b/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift @@ -5181,6 +5181,384 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } + func testServerWithNoVariables() throws { + try self.assertServersTranslation( + """ + - url: https://example.com/api + """, + """ + public enum Servers { + public static func server1() throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://example.com/api", + variables: [] + ) + } + } + """ + ) + } + + func testServerWithNoVariablesAndFeatureFlagEnabled() throws { + try self.assertServersTranslation( + """ + - url: https://example.com/api + """, + """ + public enum Servers { + public static func server1() throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://example.com/api", + variables: [] + ) + } + } + """, + featureFlags: [.serverVariablesAsEnums] + ) + } + + func testServerWithDefaultVariable() throws { + try self.assertServersTranslation( + """ + - url: '{protocol}://example.com/api' + description: A custom domain. + variables: + protocol: + default: https + description: A network protocol. + """, + """ + public enum Servers { + public static func server1(_protocol: Swift.String = "https") throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "{protocol}://example.com/api", + variables: [ + .init( + name: "protocol", + value: _protocol + ) + ] + ) + } + } + """ + ) + } + + func testServerWithDefaultVariableAndFeatureFlagEnabled() throws { + try self.assertServersTranslation( + """ + - url: '{protocol}://example.com/api' + description: A custom domain. + variables: + protocol: + default: https + description: A network protocol. + """, + """ + public enum Servers { + public static func server1(_protocol: Swift.String = "https") throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "{protocol}://example.com/api", + variables: [ + .init( + name: "protocol", + value: _protocol + ) + ] + ) + } + } + """, + featureFlags: [.serverVariablesAsEnums] + ) + } + + func testServerWithDefaultAndEnumVariables() throws { + try self.assertServersTranslation( + """ + - url: 'https://{environment}.example.com/api/{version}' + description: A custom domain. + variables: + environment: + enum: + - production + - sandbox + default: production + version: + default: v1 + """, + """ + public enum Servers { + public static func server1( + environment: Swift.String = "production", + version: Swift.String = "v1" + ) throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://{environment}.example.com/api/{version}", + variables: [ + .init( + name: "environment", + value: environment, + allowedValues: [ + "production", + "sandbox" + ] + ), + .init( + name: "version", + value: version + ) + ] + ) + } + } + """ + ) + } + + func testServerWithDefaultAndEnumVariablesAndFeatureFlagEnabled() throws { + try self.assertServersTranslation( + """ + - url: 'https://{environment}.example.com/api/{version}' + description: A custom domain. + variables: + environment: + enum: + - production + - sandbox + default: production + version: + default: v1 + """, + """ + public enum Servers { + public enum Variables { + public enum Server1 { + @frozen public enum Environment: Swift.String { + case production + case sandbox + public static var `default`: Environment { + return Environment.production + } + } + } + } + public static func server1( + environment: Variables.Server1.Environment = Variables.Server1.Environment.default, + version: Swift.String = "v1" + ) throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://{environment}.example.com/api/{version}", + variables: [ + .init( + name: "environment", + value: environment.rawValue + ), + .init( + name: "version", + value: version + ) + ] + ) + } + } + """, + featureFlags: [.serverVariablesAsEnums] + ) + } + + func testServersMultipleServers() throws { + try self.assertServersTranslation( + """ + - url: 'https://{environment}.example.com/api/{version}' + description: A custom domain. + variables: + environment: + enum: + - production + - sandbox + default: production + version: + default: v1 + - url: 'https://{environment}.api.example.com/' + variables: + environment: + enum: + - sandbox + - develop + default: develop + - url: 'https://example.com/api/{version}' + description: Vanity URL for production.example.com/api/{version} + variables: + version: + default: v1 + - url: 'https://api.example.com/' + description: Vanity URL for production.api.example.com + """, + """ + public enum Servers { + public static func server1( + environment: Swift.String = "production", + version: Swift.String = "v1" + ) throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://{environment}.example.com/api/{version}", + variables: [ + .init( + name: "environment", + value: environment, + allowedValues: [ + "production", + "sandbox" + ] + ), + .init( + name: "version", + value: version + ) + ] + ) + } + public static func server2(environment: Swift.String = "develop") throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://{environment}.api.example.com/", + variables: [ + .init( + name: "environment", + value: environment, + allowedValues: [ + "sandbox", + "develop" + ] + ) + ] + ) + } + public static func server3(version: Swift.String = "v1") throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://example.com/api/{version}", + variables: [ + .init( + name: "version", + value: version + ) + ] + ) + } + public static func server4() throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://api.example.com/", + variables: [] + ) + } + } + """ + ) + } + + func testServersMultipleServersWithFeatureFlagEnabled() throws { + try self.assertServersTranslation( + """ + - url: 'https://{environment}.example.com/api/{version}' + description: A custom domain. + variables: + environment: + enum: + - production + - sandbox + default: production + version: + default: v1 + - url: 'https://{environment}.api.example.com/' + variables: + environment: + enum: + - sandbox + - develop + default: develop + - url: 'https://example.com/api/{version}' + description: Vanity URL for production.example.com/api/{version} + variables: + version: + default: v1 + - url: 'https://api.example.com/' + description: Vanity URL for production.api.example.com + """, + """ + public enum Servers { + public enum Variables { + public enum Server1 { + @frozen public enum Environment: Swift.String { + case production + case sandbox + public static var `default`: Environment { + return Environment.production + } + } + } + public enum Server2 { + @frozen public enum Environment: Swift.String { + case sandbox + case develop + public static var `default`: Environment { + return Environment.develop + } + } + } + } + public static func server1( + environment: Variables.Server1.Environment = Variables.Server1.Environment.default, + version: Swift.String = "v1" + ) throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://{environment}.example.com/api/{version}", + variables: [ + .init( + name: "environment", + value: environment.rawValue + ), + .init( + name: "version", + value: version + ) + ] + ) + } + public static func server2(environment: Variables.Server2.Environment = Variables.Server2.Environment.default) throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://{environment}.api.example.com/", + variables: [ + .init( + name: "environment", + value: environment.rawValue + ) + ] + ) + } + public static func server3(version: Swift.String = "v1") throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://example.com/api/{version}", + variables: [ + .init( + name: "version", + value: version + ) + ] + ) + } + public static func server4() throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://api.example.com/", + variables: [] + ) + } + } + """, + featureFlags: [.serverVariablesAsEnums] + ) + } } extension SnippetBasedReferenceTests { @@ -5206,6 +5584,19 @@ extension SnippetBasedReferenceTests { components: components ) } + + func makeTypesTranslator( + accessModifier: AccessModifier = .public, + featureFlags: FeatureFlags = [], + ignoredDiagnosticMessages: Set = [], + components: OpenAPI.Components = .noComponents + ) throws -> TypesFileTranslator { + return TypesFileTranslator( + config: Config(mode: .types, access: accessModifier, featureFlags: featureFlags), + diagnostics: XCTestDiagnosticCollector(test: self, ignoredDiagnosticMessages: ignoredDiagnosticMessages), + components: components + ) + } func makeTranslators( components: OpenAPI.Components = .noComponents, @@ -5473,6 +5864,21 @@ extension SnippetBasedReferenceTests { let (registerHandlersDecl, _) = try translator.translateRegisterHandlers(operations) try XCTAssertSwiftEquivalent(registerHandlersDecl, expectedSwift, file: file, line: line) } + + func assertServersTranslation( + _ serversYAML: String, + _ expectedSwift: String, + accessModifier: AccessModifier = .public, + featureFlags: FeatureFlags = [], + file: StaticString = #filePath, + line: UInt = #line + ) throws { + continueAfterFailure = false + let servers = try YAMLDecoder().decode([OpenAPI.Server].self, from: serversYAML) + let translator = try makeTypesTranslator(accessModifier: accessModifier, featureFlags: featureFlags) + let translation = translator.translateServers(servers) + try XCTAssertSwiftEquivalent(translation, expectedSwift, file: file, line: line) + } } private func XCTAssertEqualWithDiff( From 924362c73de6c5996eb4a6382adadc0d837d2ad9 Mon Sep 17 00:00:00 2001 From: theoriginalbit <1377564+theoriginalbit@users.noreply.github.com> Date: Sat, 28 Sep 2024 20:25:57 +1000 Subject: [PATCH 06/13] Adopt approach that does not require feature flags --- .../_OpenAPIGeneratorCore/FeatureFlags.swift | 4 - .../StructuredSwiftRepresentation.swift | 4 +- .../Translator/CommonTypes/Constants.swift | 11 +- .../TypesTranslator/translateServers.swift | 121 ++++--- .../translateServersVariables.swift | 170 +++------- .../ReferenceSources/Petstore/Types.swift | 62 ++++ .../SnippetBasedReferenceTests.swift | 313 +++++++----------- 7 files changed, 296 insertions(+), 389 deletions(-) diff --git a/Sources/_OpenAPIGeneratorCore/FeatureFlags.swift b/Sources/_OpenAPIGeneratorCore/FeatureFlags.swift index 20eb7715..ca3d5682 100644 --- a/Sources/_OpenAPIGeneratorCore/FeatureFlags.swift +++ b/Sources/_OpenAPIGeneratorCore/FeatureFlags.swift @@ -28,10 +28,6 @@ public enum FeatureFlag: String, Hashable, Codable, CaseIterable, Sendable { // needs to be here for the enum to compile case empty - - /// When enabled any server URL templating variables that have a defined - /// enum field will be generated as an enum instead of raw Strings. - case serverVariablesAsEnums } /// A set of enabled feature flags. diff --git a/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift b/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift index 4cf1dab0..c37c5c0a 100644 --- a/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift +++ b/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift @@ -1629,8 +1629,8 @@ extension KeywordKind { extension Declaration { /// Returns a new deprecated variant of the declaration if `shouldDeprecate` is true. - func deprecate(if shouldDeprecate: Bool) -> Self { - if shouldDeprecate { return .deprecated(.init(), self) } + func deprecate(if shouldDeprecate: Bool, description: @autoclosure () -> DeprecationDescription = .init()) -> Self { + if shouldDeprecate { return .deprecated(description(), self) } return self } diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift index 8231fb69..c66fb904 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift @@ -56,15 +56,12 @@ enum Constants { /// The prefix of each generated method name. static let propertyPrefix: String = "server" - - /// The name of the server variables namespace. - static let variablesNamespace: String = "Variables" + + /// The name of each generated static function. + static let urlStaticFunc: String = "url" /// The prefix of the namespace that contains server specific variables. - static let serverVariablesNamespacePrefix: String = "Server" - - /// The name of the generated default computed property. - static let defaultPropertyName: String = "default" + static let serverNamespacePrefix: String = "Server" } /// Constants related to the configuration type, which is used by both diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift index eaa7efd4..e27b7f75 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift @@ -14,37 +14,19 @@ import OpenAPIKit extension TypesFileTranslator { - /// Returns a declaration of a server URL static method defined in - /// the OpenAPI document. Also appends server variables enums - /// into the variables namespace parameter, if any enums were - /// generated. - /// - Parameters: - /// - index: The index of the server in the list of servers defined - /// in the OpenAPI document. - /// - server: The server URL information. - /// - variablesNamespace: The enum namespace which is to contain - /// any variable enum definitions that may be required. - /// - Returns: A static method declaration, and a name for the variable to - /// declare the method under. - func translateServer(index: Int, server: OpenAPI.Server, variablesNamespace: inout EnumDescription) -> Declaration { - let serverVariables = translateServerVariableNamespace(index: index, server: server, variablesNamespaceName: variablesNamespace.name) - - if let serverVariablesNamespace = serverVariables.decl { - variablesNamespace.members.append(serverVariablesNamespace) - } - - let parameters = serverVariables.variables.map(\.parameter) - let variableInitializers = serverVariables.variables.map(\.initializer) - let functionComments = serverVariables.variables.map(\.functionComment) - - let methodName = "\(Constants.ServerURL.propertyPrefix)\(index + 1)" - - let methodDecl = Declaration.commentable( - .functionComment(abstract: server.description, parameters: functionComments), + func translateServerStaticFunction( + isDeprecated: Bool, + abstract: String?, + name: String, + url: String, + variableGenerators variables: [any ServerVariableGenerator] + ) -> Declaration { + return .commentable( + .functionComment(abstract: abstract, parameters: variables.map(\.functionComment)), .function( accessModifier: config.access, - kind: .function(name: methodName, isStatic: true), - parameters: parameters, + kind: .function(name: name, isStatic: true), + parameters: variables.map(\.parameter), keywords: [.throws], returnType: .identifierType(TypeName.url), body: [ @@ -54,15 +36,70 @@ extension TypesFileTranslator { .call([ .init( label: "validatingOpenAPIServerURL", - expression: .literal(.string(server.urlTemplate.absoluteString)) - ), .init(label: "variables", expression: .literal(.array(variableInitializers))), + expression: .literal(.string(url)) + ), + .init( + label: "variables", + expression: .literal(.array(variables.map(\.initializer))) + ) ]) ) ) ] + ).deprecate( + if: isDeprecated, + description: .init(message: "Migrate to the new type-safe API for server URLs.") + ) + ) + } + + /// Returns a declaration of a server URL static function defined in + /// the OpenAPI document. The function is marked as deprecated + /// with a message informing the adopter to use the new type-safe + /// API. + /// - Parameters: + /// - index: The index of the server in the list of servers defined + /// in the OpenAPI document. + /// - server: The server URL information. + /// - Returns: A static function declaration. + func translateServerAsDeprecated(index: Int, server: OpenAPI.Server) -> Declaration { + let serverVariables = translateServerVariables(index: index, server: server, generateAsEnum: false) + return translateServerStaticFunction(isDeprecated: true, + abstract: server.description, + name: "\(Constants.ServerURL.propertyPrefix)\(index + 1)", + url: server.urlTemplate.absoluteString, + variableGenerators: serverVariables) + } + + /// Returns a namespace (enum) declaration for a server defined in + /// the OpenAPI document. Within the namespace are enums to + /// represent any variables that also have enum values defined in the + /// OpenAPI document, and a single static function named 'url' which + /// at runtime returns the resolved server URL. + /// + /// The server's namespace is named to identify the human-friendly + /// index of the enum (e.g. Server1) and is present to ensure each + /// server definition's variables do not conflict with one another. + /// - Parameters: + /// - index: The index of the server in the list of servers defined + /// in the OpenAPI document. + /// - server: The server URL information. + /// - Returns: A static function declaration. + func translateServer(index: Int, server: OpenAPI.Server) -> Declaration { + let serverVariables = translateServerVariables(index: index, server: server, generateAsEnum: true) + let methodDecl = translateServerStaticFunction(isDeprecated: false, + abstract: nil, // server.description is on the namespace now + name: Constants.ServerURL.urlStaticFunc, + url: server.urlTemplate.absoluteString, + variableGenerators: serverVariables) + return .commentable( + server.description.map(Comment.doc(_:)), + .enum( + accessModifier: config.access, + name: "\(Constants.ServerURL.serverNamespacePrefix)\(index + 1)", + members: serverVariables.compactMap(\.declaration) + CollectionOfOne(methodDecl) ) ) - return methodDecl } /// Returns a declaration of a namespace (enum) called "Servers" that @@ -71,23 +108,13 @@ extension TypesFileTranslator { /// - Parameter servers: The servers to include in the extension. /// - Returns: A declaration of an enum namespace of the server URLs type. func translateServers(_ servers: [OpenAPI.Server]) -> Declaration { - var variablesNamespace = EnumDescription( - accessModifier: config.access, - name: Constants.ServerURL.variablesNamespace - ) - var serverDecls: [Declaration] = [] - for (index, decl) in servers.enumerated() { - let serverDecl = translateServer(index: index, server: decl, variablesNamespace: &variablesNamespace) - serverDecls.append(serverDecl) - } - - if !variablesNamespace.members.isEmpty { - serverDecls.insert(.commentable( - .doc("Server URL variables defined in the OpenAPI document."), - .enum(variablesNamespace) - ), at: 0) + for (index, server) in servers.enumerated() { + serverDecls.append(contentsOf: [ + translateServer(index: index, server: server), + translateServerAsDeprecated(index: index, server: server) + ]) } return .commentable( diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift index 437be5f3..cad6c7e1 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift @@ -14,8 +14,39 @@ import OpenAPIKit extension TypesFileTranslator { + /// Returns a declaration of a namespace (enum) for a specific server and will define + /// one enum member for each of the server's variables in the OpenAPI Document. + /// If the server does not define variables, no declaration will be generated. + /// - Parameters: + /// - index: The index of the server in the list of servers defined + /// in the OpenAPI document. + /// - server: The server variables information. + /// - Returns: A declaration of the server variables namespace, or `nil` if no + /// variables are declared. + func translateServerVariables(index: Int, server: OpenAPI.Server, generateAsEnum: Bool) -> [any ServerVariableGenerator] { + return server.variables.map { (key, variable) in + guard generateAsEnum, let enumValues = variable.enum else { + return RawStringTranslatedServerVariable( + key: key, + variable: variable, + asSwiftSafeName: swiftSafeName(for:) + ) + } + + return GeneratedEnumTranslatedServerVariable( + key: key, + variable: variable, + enumValues: enumValues, + accessModifier: config.access, + asSwiftSafeName: swiftSafeName(for:) + ) + } + } + + // MARK: Generators + /// Represents a server variable and the function of generation that should be applied. - protocol TranslatedServerVariable { + protocol ServerVariableGenerator { /// Returns the declaration (enum) that should be added to the `Variables.Server#` /// namespace. If the server variable does not require any codegen then it should /// return `nil`. @@ -34,101 +65,8 @@ extension TypesFileTranslator { var functionComment: (name: String, comment: String?) { get } } - /// Returns a declaration of a variable enum case for the provided value. If the value can be - /// safely represented as an identifier then the enum case is name only, otherwise the case - /// will have a raw value set to the provided value to satisfy the OpenAPI document - /// requirements. - /// - Parameter value: The variable's enum value. - /// - Returns: A enum case declaration named by the supplied value. - func translateVariableCase(_ value: String) -> Declaration { - let caseName = swiftSafeName(for: value) - if caseName == value { - return .enumCase(name: caseName, kind: .nameOnly) - } else { - return .enumCase(name: caseName, kind: .nameWithRawValue(.string(value))) - } - } - - /// Returns a declaration of a variable enum defined in the OpenAPI document. Including - /// a static computed property named default which returns the default defined in the - /// document. - /// - Parameter variable: The variable information. - /// - Returns: An enum declaration. - func translateServerVariable(key: String, variable: OpenAPI.Server.Variable, variablesNamespaceName: String, serverVariableNamespaceName: String) -> any TranslatedServerVariable { - guard variable.enum != nil, config.featureFlags.contains(.serverVariablesAsEnums) else { - return RawStringTranslatedServerVariable( - key: key, - variable: variable, - asSwiftSafeName: swiftSafeName(for:) - ) - } - - return GeneratedEnumTranslatedServerVariable( - key: key, - variable: variable, - variablesNamespaceName: variablesNamespaceName, - serverVariablesNamespaceName: serverVariableNamespaceName, - accessModifier: config.access, - asSwiftSafeName: swiftSafeName(for:) - ) - } - - /// Returns a declaration of a namespace (enum) for a specific server and will define - /// one enum member for each of the server's variables in the OpenAPI Document. - /// If the server does not define variables, no declaration will be generated. - /// - Parameters: - /// - index: The index of the server in the list of servers defined - /// in the OpenAPI document. - /// - server: The server variables information. - /// - Returns: A declaration of the server variables namespace, or `nil` if no - /// variables are declared. - func translateServerVariableNamespace(index: Int, server: OpenAPI.Server, variablesNamespaceName: String) -> TranslatedServerVariableNamespace { - let serverVariableNamespaceName = "\(Constants.ServerURL.serverVariablesNamespacePrefix)\(index + 1)" - let variables = server.variables.map { variableEntry in - translateServerVariable( - key: variableEntry.0, - variable: variableEntry.1, - variablesNamespaceName: variablesNamespaceName, - serverVariableNamespaceName: serverVariableNamespaceName - ) - } - - return TranslatedServerVariableNamespace( - index: index, - name: serverVariableNamespaceName, - accessModifier: config.access, - variables: variables - ) - } - - // MARK: Generators - - /// Represents a namespace (enum) that contains all the defined variables for a given server. - /// If none of the variables have a - struct TranslatedServerVariableNamespace { - let index: Int - let name: String - let accessModifier: AccessModifier - let variables: [any TranslatedServerVariable] - - var decl: Declaration? { - let variableDecls = variables.compactMap(\.declaration) - if variableDecls.isEmpty { - return nil - } - return .commentable( - .doc("The variables for Server\(index + 1) defined in the OpenAPI document."), - .enum( - accessModifier: accessModifier, - name: name, - members: variableDecls - ) - ) - } - } - /// Represents a variable that is required to be represented as a `Swift.String`. - private struct RawStringTranslatedServerVariable: TranslatedServerVariable { + private struct RawStringTranslatedServerVariable: ServerVariableGenerator { let key: String let swiftSafeKey: String let variable: OpenAPI.Server.Variable @@ -179,25 +117,23 @@ extension TypesFileTranslator { /// Represents a variable that will be generated as an enum and added to the `Variables.Server#` /// namespace. The enum will contain a `default` static case which returns the default defined in /// the OpenAPI Document. - private struct GeneratedEnumTranslatedServerVariable: TranslatedServerVariable { + private struct GeneratedEnumTranslatedServerVariable: ServerVariableGenerator { let key: String let swiftSafeKey: String let enumName: String let variable: OpenAPI.Server.Variable + let enumValues: [String] - let variablesNamespaceName: String - let serverVariablesNamespaceName: String let accessModifier: AccessModifier let asSwiftSafeName: (String) -> String - init(key: String, variable: OpenAPI.Server.Variable, variablesNamespaceName: String, serverVariablesNamespaceName: String, accessModifier: AccessModifier, asSwiftSafeName: @escaping (String) -> String) { + init(key: String, variable: OpenAPI.Server.Variable, enumValues: [String], accessModifier: AccessModifier, asSwiftSafeName: @escaping (String) -> String) { self.key = key swiftSafeKey = asSwiftSafeName(key) enumName = asSwiftSafeName(key.localizedCapitalized) self.variable = variable + self.enumValues = enumValues - self.variablesNamespaceName = variablesNamespaceName - self.serverVariablesNamespaceName = serverVariablesNamespaceName self.asSwiftSafeName = asSwiftSafeName self.accessModifier = accessModifier } @@ -210,28 +146,6 @@ extension TypesFileTranslator { } else { "" } - let casesDecls = variable.enum!.map(translateVariableCase) + CollectionOfOne( - .commentable( - .doc("The default variable."), - .variable( - accessModifier: accessModifier, - isStatic: true, - kind: .var, - left: .identifierPattern("`\(Constants.ServerURL.defaultPropertyName)`"), - type: .member(enumName), - getter: [ - .expression( - .return( - .memberAccess(.init( - left: .identifierPattern(enumName), - right: asSwiftSafeName(variable.default) - )) - ) - ), - ] - ) - ) - ) return .commentable( .doc(""" @@ -244,7 +158,7 @@ extension TypesFileTranslator { conformances: [ TypeName.string.fullyQualifiedSwiftName, ], - members: casesDecls + members: enumValues.map(translateVariableCase) ) ) } @@ -252,16 +166,14 @@ extension TypesFileTranslator { /// Returns the description of the parameter that will be used to define the variable /// in the static method for a given server. var parameter: ParameterDescription { + let safeDefault = asSwiftSafeName(variable.default) let memberPath: [String] = [ - variablesNamespaceName, - serverVariablesNamespaceName, - enumName, + enumName ] - return .init( label: swiftSafeKey, type: .member(memberPath), - defaultValue: .identifierType(.member(memberPath + CollectionOfOne(Constants.ServerURL.defaultPropertyName))) + defaultValue: .identifierType(.member(memberPath + CollectionOfOne(safeDefault))) ) } diff --git a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift index 818aff50..5b357b45 100644 --- a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift +++ b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift @@ -154,12 +154,31 @@ extension APIProtocol { /// Server URLs defined in the OpenAPI document. public enum Servers { /// Example Petstore implementation service + public enum Server1 { + public static func url() throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://example.com/api", + variables: [] + ) + } + } + /// Example Petstore implementation service + @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") public static func server1() throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "https://example.com/api", variables: [] ) } + public enum Server2 { + public static func url() throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "/api", + variables: [] + ) + } + } + @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") public static func server2() throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "/api", @@ -167,12 +186,55 @@ public enum Servers { ) } /// A custom domain. + public enum Server3 { + /// The "port" variable defined in the OpenAPI document. The default value is "443". + @frozen public enum Port: Swift.String { + case _443 = "443" + case _8443 = "8443" + } + /// + /// - Parameters: + /// - _protocol: + /// - subdomain: A subdomain name. + /// - port: + /// - basePath: The base API path. + public static func url( + _protocol: Swift.String = "https", + subdomain: Swift.String = "test", + port: Port = Port._443, + basePath: Swift.String = "v1" + ) throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "{protocol}://{subdomain}.example.com:{port}/{basePath}", + variables: [ + .init( + name: "protocol", + value: _protocol + ), + .init( + name: "subdomain", + value: subdomain + ), + .init( + name: "port", + value: port.rawValue + ), + .init( + name: "basePath", + value: basePath + ) + ] + ) + } + } + /// A custom domain. /// /// - Parameters: /// - _protocol: /// - subdomain: A subdomain name. /// - port: /// - basePath: The base API path. + @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") public static func server3( _protocol: Swift.String = "https", subdomain: Swift.String = "test", diff --git a/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift b/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift index 7ed2ae4d..eeec53e7 100644 --- a/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift +++ b/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift @@ -5188,24 +5188,15 @@ final class SnippetBasedReferenceTests: XCTestCase { """, """ public enum Servers { - public static func server1() throws -> Foundation.URL { - try Foundation.URL( - validatingOpenAPIServerURL: "https://example.com/api", - variables: [] - ) + public enum Server1 { + public static func url() throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://example.com/api", + variables: [] + ) + } } - } - """ - ) - } - - func testServerWithNoVariablesAndFeatureFlagEnabled() throws { - try self.assertServersTranslation( - """ - - url: https://example.com/api - """, - """ - public enum Servers { + @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") public static func server1() throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "https://example.com/api", @@ -5213,8 +5204,7 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } } - """, - featureFlags: [.serverVariablesAsEnums] + """ ) } @@ -5230,34 +5220,20 @@ final class SnippetBasedReferenceTests: XCTestCase { """, """ public enum Servers { - public static func server1(_protocol: Swift.String = "https") throws -> Foundation.URL { - try Foundation.URL( - validatingOpenAPIServerURL: "{protocol}://example.com/api", - variables: [ - .init( - name: "protocol", - value: _protocol - ) - ] - ) + public enum Server1 { + public static func url(_protocol: Swift.String = "https") throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "{protocol}://example.com/api", + variables: [ + .init( + name: "protocol", + value: _protocol + ) + ] + ) + } } - } - """ - ) - } - - func testServerWithDefaultVariableAndFeatureFlagEnabled() throws { - try self.assertServersTranslation( - """ - - url: '{protocol}://example.com/api' - description: A custom domain. - variables: - protocol: - default: https - description: A network protocol. - """, - """ - public enum Servers { + @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") public static func server1(_protocol: Swift.String = "https") throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "{protocol}://example.com/api", @@ -5270,8 +5246,7 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } } - """, - featureFlags: [.serverVariablesAsEnums] + """ ) } @@ -5291,6 +5266,31 @@ final class SnippetBasedReferenceTests: XCTestCase { """, """ public enum Servers { + public enum Server1 { + @frozen public enum Environment: Swift.String { + case production + case sandbox + } + public static func url( + environment: Environment = Environment.production, + version: Swift.String = "v1" + ) throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://{environment}.example.com/api/{version}", + variables: [ + .init( + name: "environment", + value: environment.rawValue + ), + .init( + name: "version", + value: version + ) + ] + ) + } + } + @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") public static func server1( environment: Swift.String = "production", version: Swift.String = "v1" @@ -5318,57 +5318,6 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } - func testServerWithDefaultAndEnumVariablesAndFeatureFlagEnabled() throws { - try self.assertServersTranslation( - """ - - url: 'https://{environment}.example.com/api/{version}' - description: A custom domain. - variables: - environment: - enum: - - production - - sandbox - default: production - version: - default: v1 - """, - """ - public enum Servers { - public enum Variables { - public enum Server1 { - @frozen public enum Environment: Swift.String { - case production - case sandbox - public static var `default`: Environment { - return Environment.production - } - } - } - } - public static func server1( - environment: Variables.Server1.Environment = Variables.Server1.Environment.default, - version: Swift.String = "v1" - ) throws -> Foundation.URL { - try Foundation.URL( - validatingOpenAPIServerURL: "https://{environment}.example.com/api/{version}", - variables: [ - .init( - name: "environment", - value: environment.rawValue - ), - .init( - name: "version", - value: version - ) - ] - ) - } - } - """, - featureFlags: [.serverVariablesAsEnums] - ) - } - func testServersMultipleServers() throws { try self.assertServersTranslation( """ @@ -5399,6 +5348,31 @@ final class SnippetBasedReferenceTests: XCTestCase { """, """ public enum Servers { + public enum Server1 { + @frozen public enum Environment: Swift.String { + case production + case sandbox + } + public static func url( + environment: Environment = Environment.production, + version: Swift.String = "v1" + ) throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://{environment}.example.com/api/{version}", + variables: [ + .init( + name: "environment", + value: environment.rawValue + ), + .init( + name: "version", + value: version + ) + ] + ) + } + } + @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") public static func server1( environment: Swift.String = "production", version: Swift.String = "v1" @@ -5421,6 +5395,24 @@ final class SnippetBasedReferenceTests: XCTestCase { ] ) } + public enum Server2 { + @frozen public enum Environment: Swift.String { + case sandbox + case develop + } + public static func url(environment: Environment = Environment.develop) throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://{environment}.api.example.com/", + variables: [ + .init( + name: "environment", + value: environment.rawValue + ) + ] + ) + } + } + @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") public static func server2(environment: Swift.String = "develop") throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "https://{environment}.api.example.com/", @@ -5436,107 +5428,20 @@ final class SnippetBasedReferenceTests: XCTestCase { ] ) } - public static func server3(version: Swift.String = "v1") throws -> Foundation.URL { - try Foundation.URL( - validatingOpenAPIServerURL: "https://example.com/api/{version}", - variables: [ - .init( - name: "version", - value: version - ) - ] - ) - } - public static func server4() throws -> Foundation.URL { - try Foundation.URL( - validatingOpenAPIServerURL: "https://api.example.com/", - variables: [] - ) - } - } - """ - ) - } - - func testServersMultipleServersWithFeatureFlagEnabled() throws { - try self.assertServersTranslation( - """ - - url: 'https://{environment}.example.com/api/{version}' - description: A custom domain. - variables: - environment: - enum: - - production - - sandbox - default: production - version: - default: v1 - - url: 'https://{environment}.api.example.com/' - variables: - environment: - enum: - - sandbox - - develop - default: develop - - url: 'https://example.com/api/{version}' - description: Vanity URL for production.example.com/api/{version} - variables: - version: - default: v1 - - url: 'https://api.example.com/' - description: Vanity URL for production.api.example.com - """, - """ - public enum Servers { - public enum Variables { - public enum Server1 { - @frozen public enum Environment: Swift.String { - case production - case sandbox - public static var `default`: Environment { - return Environment.production - } - } - } - public enum Server2 { - @frozen public enum Environment: Swift.String { - case sandbox - case develop - public static var `default`: Environment { - return Environment.develop - } - } + public enum Server3 { + public static func url(version: Swift.String = "v1") throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://example.com/api/{version}", + variables: [ + .init( + name: "version", + value: version + ) + ] + ) } } - public static func server1( - environment: Variables.Server1.Environment = Variables.Server1.Environment.default, - version: Swift.String = "v1" - ) throws -> Foundation.URL { - try Foundation.URL( - validatingOpenAPIServerURL: "https://{environment}.example.com/api/{version}", - variables: [ - .init( - name: "environment", - value: environment.rawValue - ), - .init( - name: "version", - value: version - ) - ] - ) - } - public static func server2(environment: Variables.Server2.Environment = Variables.Server2.Environment.default) throws -> Foundation.URL { - try Foundation.URL( - validatingOpenAPIServerURL: "https://{environment}.api.example.com/", - variables: [ - .init( - name: "environment", - value: environment.rawValue - ) - ] - ) - } + @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") public static func server3(version: Swift.String = "v1") throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "https://example.com/api/{version}", @@ -5548,6 +5453,15 @@ final class SnippetBasedReferenceTests: XCTestCase { ] ) } + public enum Server4 { + public static func url() throws -> Foundation.URL { + try Foundation.URL( + validatingOpenAPIServerURL: "https://api.example.com/", + variables: [] + ) + } + } + @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") public static func server4() throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "https://api.example.com/", @@ -5555,8 +5469,7 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } } - """, - featureFlags: [.serverVariablesAsEnums] + """ ) } } From 4d30ace3dbbbaaa8e284222697bf4ef777cd7722 Mon Sep 17 00:00:00 2001 From: theoriginalbit <1377564+theoriginalbit@users.noreply.github.com> Date: Sun, 6 Oct 2024 11:30:18 +1100 Subject: [PATCH 07/13] Address review feedback --- .../StructuredSwiftRepresentation.swift | 6 +++ .../TypesTranslator/translateServers.swift | 42 ++++++++++--------- .../translateServersVariables.swift | 8 +--- .../ReferenceSources/Petstore/Types.swift | 10 +++-- .../SnippetBasedReferenceTests.swift | 20 ++++----- 5 files changed, 47 insertions(+), 39 deletions(-) diff --git a/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift b/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift index c37c5c0a..0ac2e2ee 100644 --- a/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift +++ b/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift @@ -1628,6 +1628,12 @@ extension KeywordKind { } extension Declaration { + /// Returns a new deprecated variant of the declaration if `shouldDeprecate` is true. + func deprecate(if description: DeprecationDescription?) -> Self { + if let description { return .deprecated(description, self) } + return self + } + /// Returns a new deprecated variant of the declaration if `shouldDeprecate` is true. func deprecate(if shouldDeprecate: Bool, description: @autoclosure () -> DeprecationDescription = .init()) -> Self { if shouldDeprecate { return .deprecated(description(), self) } diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift index e27b7f75..a5a80738 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift @@ -14,8 +14,8 @@ import OpenAPIKit extension TypesFileTranslator { - func translateServerStaticFunction( - isDeprecated: Bool, + private func translateServerStaticFunction( + deprecated: DeprecationDescription?, abstract: String?, name: String, url: String, @@ -46,10 +46,7 @@ extension TypesFileTranslator { ) ) ] - ).deprecate( - if: isDeprecated, - description: .init(message: "Migrate to the new type-safe API for server URLs.") - ) + ).deprecate(if: deprecated) ) } @@ -62,13 +59,15 @@ extension TypesFileTranslator { /// in the OpenAPI document. /// - server: The server URL information. /// - Returns: A static function declaration. - func translateServerAsDeprecated(index: Int, server: OpenAPI.Server) -> Declaration { + func translateServerAsDeprecated(index: Int, server: OpenAPI.Server, renamedTo pathToReplacementSymbol: String) -> Declaration { let serverVariables = translateServerVariables(index: index, server: server, generateAsEnum: false) - return translateServerStaticFunction(isDeprecated: true, - abstract: server.description, - name: "\(Constants.ServerURL.propertyPrefix)\(index + 1)", - url: server.urlTemplate.absoluteString, - variableGenerators: serverVariables) + return translateServerStaticFunction( + deprecated: DeprecationDescription(renamed: pathToReplacementSymbol), + abstract: server.description, + name: "\(Constants.ServerURL.propertyPrefix)\(index + 1)", + url: server.urlTemplate.absoluteString, + variableGenerators: serverVariables + ) } /// Returns a namespace (enum) declaration for a server defined in @@ -85,21 +84,25 @@ extension TypesFileTranslator { /// in the OpenAPI document. /// - server: The server URL information. /// - Returns: A static function declaration. - func translateServer(index: Int, server: OpenAPI.Server) -> Declaration { + func translateServer(index: Int, server: OpenAPI.Server) -> (pathToStaticFunction: String, decl: Declaration) { let serverVariables = translateServerVariables(index: index, server: server, generateAsEnum: true) - let methodDecl = translateServerStaticFunction(isDeprecated: false, - abstract: nil, // server.description is on the namespace now + let methodDecl = translateServerStaticFunction(deprecated: nil, + abstract: server.description, name: Constants.ServerURL.urlStaticFunc, url: server.urlTemplate.absoluteString, variableGenerators: serverVariables) - return .commentable( + + let namespaceName = "\(Constants.ServerURL.serverNamespacePrefix)\(index + 1)" + let typeName = TypeName(swiftKeyPath: [Constants.ServerURL.namespace, namespaceName, Constants.ServerURL.urlStaticFunc]) + let decl = Declaration.commentable( server.description.map(Comment.doc(_:)), .enum( accessModifier: config.access, - name: "\(Constants.ServerURL.serverNamespacePrefix)\(index + 1)", + name: namespaceName, members: serverVariables.compactMap(\.declaration) + CollectionOfOne(methodDecl) ) ) + return (pathToStaticFunction: typeName.fullyQualifiedSwiftName, decl: decl) } /// Returns a declaration of a namespace (enum) called "Servers" that @@ -111,9 +114,10 @@ extension TypesFileTranslator { var serverDecls: [Declaration] = [] for (index, server) in servers.enumerated() { + let translatedServer = translateServer(index: index, server: server) serverDecls.append(contentsOf: [ - translateServer(index: index, server: server), - translateServerAsDeprecated(index: index, server: server) + translatedServer.decl, + translateServerAsDeprecated(index: index, server: server, renamedTo: translatedServer.pathToStaticFunction) ]) } diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift index 77346233..29f3d8c2 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift @@ -166,14 +166,10 @@ extension TypesFileTranslator { /// Returns the description of the parameter that will be used to define the variable /// in the static method for a given server. var parameter: ParameterDescription { - let safeDefault = context.asSwiftSafeName(variable.default) - let memberPath: [String] = [ - enumName - ] return .init( label: swiftSafeKey, - type: .member(memberPath), - defaultValue: .identifierType(.member(memberPath + CollectionOfOne(safeDefault))) + type: .member([enumName]), + defaultValue: .memberAccess(.dot(context.asSwiftSafeName(variable.default))) ) } diff --git a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift index 5b357b45..0f216252 100644 --- a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift +++ b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift @@ -155,6 +155,7 @@ extension APIProtocol { public enum Servers { /// Example Petstore implementation service public enum Server1 { + /// Example Petstore implementation service public static func url() throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "https://example.com/api", @@ -163,7 +164,7 @@ public enum Servers { } } /// Example Petstore implementation service - @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") + @available(*, deprecated, renamed: "Servers.Server1.url") public static func server1() throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "https://example.com/api", @@ -178,7 +179,7 @@ public enum Servers { ) } } - @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") + @available(*, deprecated, renamed: "Servers.Server2.url") public static func server2() throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "/api", @@ -192,6 +193,7 @@ public enum Servers { case _443 = "443" case _8443 = "8443" } + /// A custom domain. /// /// - Parameters: /// - _protocol: @@ -201,7 +203,7 @@ public enum Servers { public static func url( _protocol: Swift.String = "https", subdomain: Swift.String = "test", - port: Port = Port._443, + port: Port = ._443, basePath: Swift.String = "v1" ) throws -> Foundation.URL { try Foundation.URL( @@ -234,7 +236,7 @@ public enum Servers { /// - subdomain: A subdomain name. /// - port: /// - basePath: The base API path. - @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") + @available(*, deprecated, renamed: "Servers.Server3.url") public static func server3( _protocol: Swift.String = "https", subdomain: Swift.String = "test", diff --git a/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift b/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift index c29f15be..7df0b2e1 100644 --- a/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift +++ b/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift @@ -5196,7 +5196,7 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } } - @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") + @available(*, deprecated, renamed: "Servers.Server1.url") public static func server1() throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "https://example.com/api", @@ -5233,7 +5233,7 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } } - @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") + @available(*, deprecated, renamed: "Servers.Server1.url") public static func server1(_protocol: Swift.String = "https") throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "{protocol}://example.com/api", @@ -5272,7 +5272,7 @@ final class SnippetBasedReferenceTests: XCTestCase { case sandbox } public static func url( - environment: Environment = Environment.production, + environment: Environment = .production, version: Swift.String = "v1" ) throws -> Foundation.URL { try Foundation.URL( @@ -5290,7 +5290,7 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } } - @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") + @available(*, deprecated, renamed: "Servers.Server1.url") public static func server1( environment: Swift.String = "production", version: Swift.String = "v1" @@ -5354,7 +5354,7 @@ final class SnippetBasedReferenceTests: XCTestCase { case sandbox } public static func url( - environment: Environment = Environment.production, + environment: Environment = .production, version: Swift.String = "v1" ) throws -> Foundation.URL { try Foundation.URL( @@ -5372,7 +5372,7 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } } - @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") + @available(*, deprecated, renamed: "Servers.Server1.url") public static func server1( environment: Swift.String = "production", version: Swift.String = "v1" @@ -5400,7 +5400,7 @@ final class SnippetBasedReferenceTests: XCTestCase { case sandbox case develop } - public static func url(environment: Environment = Environment.develop) throws -> Foundation.URL { + public static func url(environment: Environment = .develop) throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "https://{environment}.api.example.com/", variables: [ @@ -5412,7 +5412,7 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } } - @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") + @available(*, deprecated, renamed: "Servers.Server2.url") public static func server2(environment: Swift.String = "develop") throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "https://{environment}.api.example.com/", @@ -5441,7 +5441,7 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } } - @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") + @available(*, deprecated, renamed: "Servers.Server3.url") public static func server3(version: Swift.String = "v1") throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "https://example.com/api/{version}", @@ -5461,7 +5461,7 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } } - @available(*, deprecated, message: "Migrate to the new type-safe API for server URLs.") + @available(*, deprecated, renamed: "Servers.Server4.url") public static func server4() throws -> Foundation.URL { try Foundation.URL( validatingOpenAPIServerURL: "https://api.example.com/", From d875fe41f1c32b4888acf68fe210039b329a9328 Mon Sep 17 00:00:00 2001 From: theoriginalbit <1377564+theoriginalbit@users.noreply.github.com> Date: Wed, 9 Oct 2024 22:25:25 +1100 Subject: [PATCH 08/13] Add missing comments to the new implementations --- .../StructuredSwiftRepresentation.swift | 2 +- .../TypesTranslator/translateServers.swift | 61 +++++++++++----- .../translateServersVariables.swift | 73 ++++++++++++++----- 3 files changed, 96 insertions(+), 40 deletions(-) diff --git a/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift b/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift index 0ac2e2ee..6be4a80f 100644 --- a/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift +++ b/Sources/_OpenAPIGeneratorCore/Layers/StructuredSwiftRepresentation.swift @@ -1628,7 +1628,7 @@ extension KeywordKind { } extension Declaration { - /// Returns a new deprecated variant of the declaration if `shouldDeprecate` is true. + /// Returns a new deprecated variant of the declaration if the provided `description` is not `nil`. func deprecate(if description: DeprecationDescription?) -> Self { if let description { return .deprecated(description, self) } return self diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift index a5a80738..3e7e063a 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift @@ -14,15 +14,42 @@ import OpenAPIKit extension TypesFileTranslator { + /// Returns a declaration of a server URL static function defined in + /// the OpenAPI document using the supplied name identifier and + /// variable generators. + /// + /// If the `deprecated` parameter is supplied the static function + /// will be generated with a name that matches the previous, now + /// deprecated API. + /// + /// - Important: The variable generators provided should all + /// be ``RawStringTranslatedServerVariable`` to ensure + /// the generated function matches the previous implementation, this + /// is **not** asserted by this translate function. + /// + /// If the `deprecated` parameter is `nil` then the function will + /// be generated with the identifier `url` and must be a member + /// of a namespace to avoid conflicts with other server URL static + /// functions. + /// + /// - Parameters: + /// - index: The index of the server in the list of servers defined + /// in the OpenAPI document. + /// - server: The server URL information. + /// - deprecated: A deprecation `@available` annotation to attach + /// to this declaration, or `nil` if the declaration should not be deprecated. + /// - variables: The generators for variables the server has defined. + /// - Returns: A static method declaration, and a name for the variable to + /// declare the method under. private func translateServerStaticFunction( + index: Int, + server: OpenAPI.Server, deprecated: DeprecationDescription?, - abstract: String?, - name: String, - url: String, variableGenerators variables: [any ServerVariableGenerator] ) -> Declaration { + let name = deprecated == nil ? Constants.ServerURL.urlStaticFunc : "\(Constants.ServerURL.propertyPrefix)\(index + 1)" return .commentable( - .functionComment(abstract: abstract, parameters: variables.map(\.functionComment)), + .functionComment(abstract: server.description, parameters: variables.map(\.functionComment)), .function( accessModifier: config.access, kind: .function(name: name, isStatic: true), @@ -36,7 +63,7 @@ extension TypesFileTranslator { .call([ .init( label: "validatingOpenAPIServerURL", - expression: .literal(.string(url)) + expression: .literal(.string(server.urlTemplate.absoluteString)) ), .init( label: "variables", @@ -61,13 +88,10 @@ extension TypesFileTranslator { /// - Returns: A static function declaration. func translateServerAsDeprecated(index: Int, server: OpenAPI.Server, renamedTo pathToReplacementSymbol: String) -> Declaration { let serverVariables = translateServerVariables(index: index, server: server, generateAsEnum: false) - return translateServerStaticFunction( - deprecated: DeprecationDescription(renamed: pathToReplacementSymbol), - abstract: server.description, - name: "\(Constants.ServerURL.propertyPrefix)\(index + 1)", - url: server.urlTemplate.absoluteString, - variableGenerators: serverVariables - ) + return translateServerStaticFunction(index: index, + server: server, + deprecated: DeprecationDescription(renamed: pathToReplacementSymbol), + variableGenerators: serverVariables) } /// Returns a namespace (enum) declaration for a server defined in @@ -86,12 +110,11 @@ extension TypesFileTranslator { /// - Returns: A static function declaration. func translateServer(index: Int, server: OpenAPI.Server) -> (pathToStaticFunction: String, decl: Declaration) { let serverVariables = translateServerVariables(index: index, server: server, generateAsEnum: true) - let methodDecl = translateServerStaticFunction(deprecated: nil, - abstract: server.description, - name: Constants.ServerURL.urlStaticFunc, - url: server.urlTemplate.absoluteString, + let methodDecl = translateServerStaticFunction(index: index, + server: server, + deprecated: nil, variableGenerators: serverVariables) - + let namespaceName = "\(Constants.ServerURL.serverNamespacePrefix)\(index + 1)" let typeName = TypeName(swiftKeyPath: [Constants.ServerURL.namespace, namespaceName, Constants.ServerURL.urlStaticFunc]) let decl = Declaration.commentable( @@ -112,7 +135,7 @@ extension TypesFileTranslator { /// - Returns: A declaration of an enum namespace of the server URLs type. func translateServers(_ servers: [OpenAPI.Server]) -> Declaration { var serverDecls: [Declaration] = [] - + for (index, server) in servers.enumerated() { let translatedServer = translateServer(index: index, server: server) serverDecls.append(contentsOf: [ @@ -120,7 +143,7 @@ extension TypesFileTranslator { translateServerAsDeprecated(index: index, server: server, renamedTo: translatedServer.pathToStaticFunction) ]) } - + return .commentable( .doc("Server URLs defined in the OpenAPI document."), .enum(accessModifier: config.access, name: Constants.ServerURL.namespace, members: serverDecls) diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift index 29f3d8c2..5dcc7421 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift @@ -24,7 +24,7 @@ extension TypesFileTranslator { /// - Returns: A declaration of the server variables namespace, or `nil` if no /// variables are declared. func translateServerVariables(index: Int, server: OpenAPI.Server, generateAsEnum: Bool) -> [any ServerVariableGenerator] { - return server.variables.map { (key, variable) in + return server.variables.map { key, variable in guard generateAsEnum, let enumValues = variable.enum else { return RawStringTranslatedServerVariable( key: key, @@ -32,7 +32,7 @@ extension TypesFileTranslator { context: context ) } - + return GeneratedEnumTranslatedServerVariable( key: key, variable: variable, @@ -47,9 +47,8 @@ extension TypesFileTranslator { /// Represents a server variable and the function of generation that should be applied. protocol ServerVariableGenerator { - /// Returns the declaration (enum) that should be added to the `Variables.Server#` - /// namespace. If the server variable does not require any codegen then it should - /// return `nil`. + /// Returns the declaration (enum) that should be added to the server's namespace. + /// If the server variable does not require any codegen then it should return `nil`. var declaration: Declaration? { get } /// Returns the description of the parameter that will be used to define the variable @@ -64,22 +63,39 @@ extension TypesFileTranslator { /// the server's static method. var functionComment: (name: String, comment: String?) { get } } - + /// Represents a variable that is required to be represented as a `Swift.String`. private struct RawStringTranslatedServerVariable: ServerVariableGenerator { + /// The key of the variable defined in the Open API document. let key: String + + /// The ``key`` after being santized for use as an identifier. let swiftSafeKey: String + + /// The server variable information. let variable: OpenAPI.Server.Variable + /// Create a generator for an Open API "Server Variable Object" that is represented + /// by a `Swift.String` in the generated output. + /// + /// - Parameters: + /// - key: The key of the variable defined in the Open API document. + /// - variable: The server variable information. + /// - context: The translator context the generator should use to create + /// Swift safe identifiers. init(key: String, variable: OpenAPI.Server.Variable, context: TranslatorContext) { self.key = key swiftSafeKey = context.asSwiftSafeName(key) self.variable = variable } - /// A variable being represented by a `Swift.String` does not have a declaration that needs to - /// be added to the `Variables.Server#` namespace. - var declaration: Declaration? { nil } + /// Returns the declaration (enum) that should be added to the server's namespace. + /// If the server variable does not require any codegen then it should return `nil`. + var declaration: Declaration? { + // A variable being represented by a `Swift.String` does not have a declaration that needs to + // be added to the server's namespace. + return nil + } /// Returns the description of the parameter that will be used to define the variable /// in the static method for a given server. @@ -114,32 +130,53 @@ extension TypesFileTranslator { } } - /// Represents a variable that will be generated as an enum and added to the `Variables.Server#` - /// namespace. The enum will contain a `default` static case which returns the default defined in - /// the OpenAPI Document. + /// Represents an Open API "Server Variable Object" that will be generated as an enum and added + /// to the server's namespace. private struct GeneratedEnumTranslatedServerVariable: ServerVariableGenerator { + /// The key of the variable defined in the Open API document. let key: String + + /// The ``key`` after being santized for use as an identifier. let swiftSafeKey: String + + /// The ``key`` after being santized for use as the enum identifier. let enumName: String + + /// The server variable information. let variable: OpenAPI.Server.Variable + + /// The 'enum' values of the variable as defined in the Open API document. let enumValues: [String] + /// The access modifier to use for generated declarations. let accessModifier: AccessModifier + + /// The translator context the generator should use to create Swift safe identifiers. let context: TranslatorContext + /// Create a generator for an Open API "Server Variable Object" that is represented + /// by an enumeration in the generated output. + /// + /// - Parameters: + /// - key: The key of the variable defined in the Open API document. + /// - variable: The server variable information. + /// - enumValues: The 'enum' values of the variable as defined in the Open API document. + /// - accessModifier: The access modifier to use for generated declarations. + /// - context: The translator context the generator should use to create + /// Swift safe identifiers. init(key: String, variable: OpenAPI.Server.Variable, enumValues: [String], accessModifier: AccessModifier, context: TranslatorContext) { self.key = key swiftSafeKey = context.asSwiftSafeName(key) enumName = context.asSwiftSafeName(key.localizedCapitalized) self.variable = variable self.enumValues = enumValues - + self.context = context self.accessModifier = accessModifier } - /// Returns the declaration (enum) that should be added to the `Variables.Server#` - /// namespace. + /// Returns the declaration (enum) that should be added to the server's namespace. + /// If the server variable does not require any codegen then it should return `nil`. var declaration: Declaration? { let description: String = if let description = variable.description { description + "\n\n" @@ -204,11 +241,7 @@ extension TypesFileTranslator { /// - Returns: A declaration of an enum case. private func translateVariableCase(_ name: String) -> Declaration { let caseName = context.asSwiftSafeName(name) - if caseName == name { - return .enumCase(name: caseName, kind: .nameOnly) - } else { - return .enumCase(name: caseName, kind: .nameWithRawValue(.string(name))) - } + return .enumCase(name: caseName, kind: caseName == name ? .nameOnly : .nameWithRawValue(.string(name))) } } } From 7156e50e9489ba76c842d7737f861554e62b0f24 Mon Sep 17 00:00:00 2001 From: theoriginalbit <1377564+theoriginalbit@users.noreply.github.com> Date: Wed, 9 Oct 2024 22:32:18 +1100 Subject: [PATCH 09/13] Generate the server variable enums as Sendable --- .../Translator/CommonTypes/Constants.swift | 7 +++++++ .../TypesTranslator/translateServersVariables.swift | 4 +--- .../Resources/ReferenceSources/Petstore/Types.swift | 2 +- .../SnippetBasedReferenceTests.swift | 6 +++--- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift index c66fb904..48c506f0 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift @@ -62,6 +62,13 @@ enum Constants { /// The prefix of the namespace that contains server specific variables. static let serverNamespacePrefix: String = "Server" + + /// Constants related to the OpenAPI server variable object. + enum Variable { + + /// The types that the protocol conforms to. + static let conformances: [String] = [TypeName.string.fullyQualifiedSwiftName, "Sendable"] + } } /// Constants related to the configuration type, which is used by both diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift index 5dcc7421..915df79c 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift @@ -192,9 +192,7 @@ extension TypesFileTranslator { isFrozen: true, accessModifier: accessModifier, name: enumName, - conformances: [ - TypeName.string.fullyQualifiedSwiftName, - ], + conformances: Constants.ServerURL.Variable.conformances, members: enumValues.map(translateVariableCase) ) ) diff --git a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift index 0f216252..2baf58a2 100644 --- a/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift +++ b/Tests/OpenAPIGeneratorReferenceTests/Resources/ReferenceSources/Petstore/Types.swift @@ -189,7 +189,7 @@ public enum Servers { /// A custom domain. public enum Server3 { /// The "port" variable defined in the OpenAPI document. The default value is "443". - @frozen public enum Port: Swift.String { + @frozen public enum Port: Swift.String, Sendable { case _443 = "443" case _8443 = "8443" } diff --git a/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift b/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift index 7df0b2e1..9775d0fe 100644 --- a/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift +++ b/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift @@ -5267,7 +5267,7 @@ final class SnippetBasedReferenceTests: XCTestCase { """ public enum Servers { public enum Server1 { - @frozen public enum Environment: Swift.String { + @frozen public enum Environment: Swift.String, Sendable { case production case sandbox } @@ -5349,7 +5349,7 @@ final class SnippetBasedReferenceTests: XCTestCase { """ public enum Servers { public enum Server1 { - @frozen public enum Environment: Swift.String { + @frozen public enum Environment: Swift.String, Sendable { case production case sandbox } @@ -5396,7 +5396,7 @@ final class SnippetBasedReferenceTests: XCTestCase { ) } public enum Server2 { - @frozen public enum Environment: Swift.String { + @frozen public enum Environment: Swift.String, Sendable { case sandbox case develop } From c62d6bdbd75012ca1170e46ba857baf2d485edb3 Mon Sep 17 00:00:00 2001 From: theoriginalbit <1377564+theoriginalbit@users.noreply.github.com> Date: Wed, 9 Oct 2024 22:48:34 +1100 Subject: [PATCH 10/13] Update tutorials and tests to reference new type-safe variables API --- .../Tutorials/ClientSwiftPM.tutorial | 2 +- .../Documentation.docc/Tutorials/ClientXcode.tutorial | 2 +- .../Tutorials/_Resources/client.main.2.swift | 2 +- .../Tutorials/_Resources/client.main.3.swift | 2 +- .../Tutorials/_Resources/client.main.4.swift | 2 +- .../Tutorials/_Resources/client.main.5.swift | 2 +- .../Tutorials/_Resources/client.main.6.swift | 2 +- .../Tutorials/_Resources/client.main.7.swift | 2 +- .../Tutorials/_Resources/client.xcode.2.swift | 2 +- .../Tutorials/_Resources/client.xcode.3.swift | 2 +- .../Tutorials/_Resources/client.xcode.4.swift | 2 +- .../Tutorials/_Resources/client.xcode.5.swift | 2 +- .../Tutorials/_Resources/client.xcode.6.2.swift | 2 +- .../Tutorials/_Resources/client.xcode.6.swift | 2 +- .../_Resources/server-openapi-endpoints.main.0.swift | 2 +- .../_Resources/server-openapi-endpoints.main.1.swift | 2 +- .../_Resources/server-openapi-endpoints.main.2.swift | 2 +- .../Tutorials/_Resources/server.main.1.2.swift | 2 +- .../Tutorials/_Resources/server.main.2.swift | 2 +- Tests/PetstoreConsumerTests/Test_Types.swift | 11 +++++++---- 20 files changed, 26 insertions(+), 23 deletions(-) diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/ClientSwiftPM.tutorial b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/ClientSwiftPM.tutorial index 734920f3..11f1a22a 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/ClientSwiftPM.tutorial +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/ClientSwiftPM.tutorial @@ -122,7 +122,7 @@ @Step { Next we'll create an instance of our client. - Note: `Servers.server2()` is the localhost service, defined in the OpenAPI document. + Note: `Servers.Server2.url()` is the localhost service, defined in the OpenAPI document. @Code(name: "main.swift", file: client.main.2.swift) } @Step { diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/ClientXcode.tutorial b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/ClientXcode.tutorial index 7e7d81ab..d9987b94 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/ClientXcode.tutorial +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/ClientXcode.tutorial @@ -119,7 +119,7 @@ @Step { Next we'll create an instance of the generated client. - Note: `Servers.server2()` is the localhost service, defined in the OpenAPI document. + Note: `Servers.Server2.url()` is the localhost service, defined in the OpenAPI document. @Code(name: "GreetingClient.swift", file: client.xcode.2.swift) } diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.2.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.2.swift index bb80bcc8..dad11f0a 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.2.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.2.swift @@ -2,6 +2,6 @@ import OpenAPIRuntime import OpenAPIURLSession let client = Client( - serverURL: try Servers.server2(), + serverURL: try Servers.Server2.url(), transport: URLSessionTransport() ) diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.3.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.3.swift index 36acbcba..9de0b4bd 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.3.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.3.swift @@ -2,7 +2,7 @@ import OpenAPIRuntime import OpenAPIURLSession let client = Client( - serverURL: try Servers.server2(), + serverURL: try Servers.Server2.url(), transport: URLSessionTransport() ) diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.4.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.4.swift index 1cb79a1b..82a02588 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.4.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.4.swift @@ -2,7 +2,7 @@ import OpenAPIRuntime import OpenAPIURLSession let client = Client( - serverURL: try Servers.server2(), + serverURL: try Servers.Server2.url(), transport: URLSessionTransport() ) diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.5.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.5.swift index 082116fc..ced62d28 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.5.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.5.swift @@ -2,7 +2,7 @@ import OpenAPIRuntime import OpenAPIURLSession let client = Client( - serverURL: try Servers.server2(), + serverURL: try Servers.Server2.url(), transport: URLSessionTransport() ) diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.6.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.6.swift index 7da6993b..f4983960 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.6.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.6.swift @@ -2,7 +2,7 @@ import OpenAPIRuntime import OpenAPIURLSession let client = Client( - serverURL: try Servers.server2(), + serverURL: try Servers.Server2.url(), transport: URLSessionTransport() ) diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.7.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.7.swift index 9b13e4e8..44c4f254 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.7.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.main.7.swift @@ -2,7 +2,7 @@ import OpenAPIRuntime import OpenAPIURLSession let client = Client( - serverURL: try Servers.server2(), + serverURL: try Servers.Server2.url(), transport: URLSessionTransport() ) diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.2.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.2.swift index 75971079..c6e25733 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.2.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.2.swift @@ -6,7 +6,7 @@ public struct GreetingClient { public func getGreeting(name: String?) async throws -> String { let client = Client( - serverURL: try Servers.server2(), + serverURL: try Servers.Server2.url(), transport: URLSessionTransport() ) } diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.3.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.3.swift index 721e2049..a5e94b38 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.3.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.3.swift @@ -6,7 +6,7 @@ public struct GreetingClient { public func getGreeting(name: String?) async throws -> String { let client = Client( - serverURL: try Servers.server2(), + serverURL: try Servers.Server2.url(), transport: URLSessionTransport() ) let response = try await client.getGreeting(query: .init(name: name)) diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.4.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.4.swift index 384f0eb2..7ac5c24b 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.4.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.4.swift @@ -6,7 +6,7 @@ public struct GreetingClient { public func getGreeting(name: String?) async throws -> String { let client = Client( - serverURL: try Servers.server2(), + serverURL: try Servers.Server2.url(), transport: URLSessionTransport() ) let response = try await client.getGreeting(query: .init(name: name)) diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.5.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.5.swift index da9d9511..3b3684ce 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.5.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.5.swift @@ -6,7 +6,7 @@ public struct GreetingClient { public func getGreeting(name: String?) async throws -> String { let client = Client( - serverURL: try Servers.server2(), + serverURL: try Servers.Server2.url(), transport: URLSessionTransport() ) let response = try await client.getGreeting(query: .init(name: name)) diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.6.2.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.6.2.swift index 33c14bd3..843dadb1 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.6.2.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.6.2.swift @@ -6,7 +6,7 @@ public struct GreetingClient { public func getGreeting(name: String?) async throws -> String { let client = Client( - serverURL: try Servers.server2(), + serverURL: try Servers.Server2.url(), transport: URLSessionTransport() ) let response = try await client.getGreeting(query: .init(name: name)) diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.6.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.6.swift index 5bd073eb..2967d27b 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.6.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.xcode.6.swift @@ -6,7 +6,7 @@ public struct GreetingClient { public func getGreeting(name: String?) async throws -> String { let client = Client( - serverURL: try Servers.server2(), + serverURL: try Servers.Server2.url(), transport: URLSessionTransport() ) let response = try await client.getGreeting(query: .init(name: name)) diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server-openapi-endpoints.main.0.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server-openapi-endpoints.main.0.swift index 86e1d8b1..6e1b07ac 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server-openapi-endpoints.main.0.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server-openapi-endpoints.main.0.swift @@ -26,7 +26,7 @@ let handler = GreetingServiceAPIImpl() // Call the generated function on your implementation to add its request // handlers to the app. -try handler.registerHandlers(on: transport, serverURL: Servers.server1()) +try handler.registerHandlers(on: transport, serverURL: Servers.Server1.url()) // Start the app as you would normally. try await app.execute() diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server-openapi-endpoints.main.1.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server-openapi-endpoints.main.1.swift index 2fe97bc9..525132bd 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server-openapi-endpoints.main.1.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server-openapi-endpoints.main.1.swift @@ -26,7 +26,7 @@ let handler = GreetingServiceAPIImpl() // Call the generated function on your implementation to add its request // handlers to the app. -try handler.registerHandlers(on: transport, serverURL: Servers.server1()) +try handler.registerHandlers(on: transport, serverURL: Servers.Server1.url()) // Add Vapor middleware to serve the contents of the Public/ directory. app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory)) diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server-openapi-endpoints.main.2.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server-openapi-endpoints.main.2.swift index 43b083d8..c1df5d52 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server-openapi-endpoints.main.2.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server-openapi-endpoints.main.2.swift @@ -26,7 +26,7 @@ let handler = GreetingServiceAPIImpl() // Call the generated function on your implementation to add its request // handlers to the app. -try handler.registerHandlers(on: transport, serverURL: Servers.server1()) +try handler.registerHandlers(on: transport, serverURL: Servers.Server1.url()) // Add Vapor middleware to serve the contents of the Public/ directory. app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory)) diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server.main.1.2.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server.main.1.2.swift index 86e1d8b1..6e1b07ac 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server.main.1.2.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server.main.1.2.swift @@ -26,7 +26,7 @@ let handler = GreetingServiceAPIImpl() // Call the generated function on your implementation to add its request // handlers to the app. -try handler.registerHandlers(on: transport, serverURL: Servers.server1()) +try handler.registerHandlers(on: transport, serverURL: Servers.Server1.url()) // Start the app as you would normally. try await app.execute() diff --git a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server.main.2.swift b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server.main.2.swift index 3d20764b..eee61a52 100644 --- a/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server.main.2.swift +++ b/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server.main.2.swift @@ -34,7 +34,7 @@ let handler = GreetingServiceAPIImpl() // Call the generated function on your implementation to add its request // handlers to the app. -try handler.registerHandlers(on: transport, serverURL: Servers.server1()) +try handler.registerHandlers(on: transport, serverURL: Servers.Server1.url()) // Start the app as you would normally. try await app.execute() diff --git a/Tests/PetstoreConsumerTests/Test_Types.swift b/Tests/PetstoreConsumerTests/Test_Types.swift index eb1822ab..b7aac29d 100644 --- a/Tests/PetstoreConsumerTests/Test_Types.swift +++ b/Tests/PetstoreConsumerTests/Test_Types.swift @@ -222,14 +222,17 @@ final class Test_Types: XCTestCase { verifyingJSON: #"{"name":"C","parent":{"nested":{"name":"B","parent":{"nested":{"name":"A"}}}}}"# ) } - func testServers_1() throws { XCTAssertEqual(try Servers.server1(), URL(string: "https://example.com/api")) } - func testServers_2() throws { XCTAssertEqual(try Servers.server2(), URL(string: "/api")) } + func testServers_1() throws { XCTAssertEqual(try Servers.Server1.url(), URL(string: "https://example.com/api")) } + func testServers_2() throws { XCTAssertEqual(try Servers.Server2.url(), URL(string: "/api")) } func testServers_3() throws { - XCTAssertEqual(try Servers.server3(), URL(string: "https://test.example.com:443/v1")) + XCTAssertEqual(try Servers.Server3.url(), URL(string: "https://test.example.com:443/v1")) XCTAssertEqual( - try Servers.server3(subdomain: "bar", port: "8443", basePath: "v2/staging"), + try Servers.Server3.url(subdomain: "bar", port: ._8443, basePath: "v2/staging"), URL(string: "https://bar.example.com:8443/v2/staging") ) + // Intentionally using the deprecated static function to check for regressions. + // Once the deprecated functions are no longer being generated this assertion is + // unnecessary and can be removed. XCTAssertThrowsError(try Servers.server3(port: "foo")) { error in guard case let .invalidServerVariableValue(name: name, value: value, allowedValues: allowedValues) = error From 4d8a719dac4ccb4cdce219f152eb2dee8f5480d4 Mon Sep 17 00:00:00 2001 From: theoriginalbit <1377564+theoriginalbit@users.noreply.github.com> Date: Thu, 10 Oct 2024 22:58:12 +1100 Subject: [PATCH 11/13] Remove no longer required test --- Tests/PetstoreConsumerTests/Test_Types.swift | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/Tests/PetstoreConsumerTests/Test_Types.swift b/Tests/PetstoreConsumerTests/Test_Types.swift index b7aac29d..7aaba0cc 100644 --- a/Tests/PetstoreConsumerTests/Test_Types.swift +++ b/Tests/PetstoreConsumerTests/Test_Types.swift @@ -230,20 +230,5 @@ final class Test_Types: XCTestCase { try Servers.Server3.url(subdomain: "bar", port: ._8443, basePath: "v2/staging"), URL(string: "https://bar.example.com:8443/v2/staging") ) - // Intentionally using the deprecated static function to check for regressions. - // Once the deprecated functions are no longer being generated this assertion is - // unnecessary and can be removed. - XCTAssertThrowsError(try Servers.server3(port: "foo")) { error in - guard - case let .invalidServerVariableValue(name: name, value: value, allowedValues: allowedValues) = error - as? RuntimeError - else { - XCTFail("Expected error, but not this: \(error)") - return - } - XCTAssertEqual(name, "port") - XCTAssertEqual(value, "foo") - XCTAssertEqual(allowedValues, ["443", "8443"]) - } } } From b559ea180c6a1b5e8cfb238071fc1b4823a4eb2a Mon Sep 17 00:00:00 2001 From: theoriginalbit <1377564+theoriginalbit@users.noreply.github.com> Date: Thu, 10 Oct 2024 23:03:09 +1100 Subject: [PATCH 12/13] Resolve code that was failing format check workflow --- .../Translator/TypesTranslator/translateServers.swift | 2 ++ .../Translator/TypesTranslator/translateServersVariables.swift | 2 ++ 2 files changed, 4 insertions(+) diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift index 3e7e063a..25d9ab53 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift @@ -85,6 +85,8 @@ extension TypesFileTranslator { /// - index: The index of the server in the list of servers defined /// in the OpenAPI document. /// - server: The server URL information. + /// - pathToReplacementSymbol: The Swift path of the symbol + /// which has resulted in the deprecation of this symbol. /// - Returns: A static function declaration. func translateServerAsDeprecated(index: Int, server: OpenAPI.Server, renamedTo pathToReplacementSymbol: String) -> Declaration { let serverVariables = translateServerVariables(index: index, server: server, generateAsEnum: false) diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift index 915df79c..42d52df5 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift @@ -21,6 +21,8 @@ extension TypesFileTranslator { /// - index: The index of the server in the list of servers defined /// in the OpenAPI document. /// - server: The server variables information. + /// - generateAsEnum: Whether the enum generator is allowed, if `false` + /// only `RawStringTranslatedServerVariable` generators will be returned. /// - Returns: A declaration of the server variables namespace, or `nil` if no /// variables are declared. func translateServerVariables(index: Int, server: OpenAPI.Server, generateAsEnum: Bool) -> [any ServerVariableGenerator] { From ecd00006ff42df7a56977447256ebd8e26081643 Mon Sep 17 00:00:00 2001 From: theoriginalbit <1377564+theoriginalbit@users.noreply.github.com> Date: Fri, 11 Oct 2024 22:24:40 +1100 Subject: [PATCH 13/13] Run linter and fix Swift 5.9 compile issue --- .../Translator/CommonTypes/Constants.swift | 1 - .../TypesTranslator/translateServers.swift | 45 ++++--- .../translateServersVariables.swift | 114 ++++++++---------- .../SnippetBasedReferenceTests.swift | 3 +- 4 files changed, 81 insertions(+), 82 deletions(-) diff --git a/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift b/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift index 48c506f0..d1fbedcf 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/CommonTypes/Constants.swift @@ -56,7 +56,6 @@ enum Constants { /// The prefix of each generated method name. static let propertyPrefix: String = "server" - /// The name of each generated static function. static let urlStaticFunc: String = "url" diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift index 25d9ab53..cf9927a7 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServers.swift @@ -47,7 +47,8 @@ extension TypesFileTranslator { deprecated: DeprecationDescription?, variableGenerators variables: [any ServerVariableGenerator] ) -> Declaration { - let name = deprecated == nil ? Constants.ServerURL.urlStaticFunc : "\(Constants.ServerURL.propertyPrefix)\(index + 1)" + let name = + deprecated == nil ? Constants.ServerURL.urlStaticFunc : "\(Constants.ServerURL.propertyPrefix)\(index + 1)" return .commentable( .functionComment(abstract: server.description, parameters: variables.map(\.functionComment)), .function( @@ -68,12 +69,13 @@ extension TypesFileTranslator { .init( label: "variables", expression: .literal(.array(variables.map(\.initializer))) - ) + ), ]) ) ) ] - ).deprecate(if: deprecated) + ) + .deprecate(if: deprecated) ) } @@ -88,12 +90,16 @@ extension TypesFileTranslator { /// - pathToReplacementSymbol: The Swift path of the symbol /// which has resulted in the deprecation of this symbol. /// - Returns: A static function declaration. - func translateServerAsDeprecated(index: Int, server: OpenAPI.Server, renamedTo pathToReplacementSymbol: String) -> Declaration { + func translateServerAsDeprecated(index: Int, server: OpenAPI.Server, renamedTo pathToReplacementSymbol: String) + -> Declaration + { let serverVariables = translateServerVariables(index: index, server: server, generateAsEnum: false) - return translateServerStaticFunction(index: index, - server: server, - deprecated: DeprecationDescription(renamed: pathToReplacementSymbol), - variableGenerators: serverVariables) + return translateServerStaticFunction( + index: index, + server: server, + deprecated: DeprecationDescription(renamed: pathToReplacementSymbol), + variableGenerators: serverVariables + ) } /// Returns a namespace (enum) declaration for a server defined in @@ -112,13 +118,16 @@ extension TypesFileTranslator { /// - Returns: A static function declaration. func translateServer(index: Int, server: OpenAPI.Server) -> (pathToStaticFunction: String, decl: Declaration) { let serverVariables = translateServerVariables(index: index, server: server, generateAsEnum: true) - let methodDecl = translateServerStaticFunction(index: index, - server: server, - deprecated: nil, - variableGenerators: serverVariables) - + let methodDecl = translateServerStaticFunction( + index: index, + server: server, + deprecated: nil, + variableGenerators: serverVariables + ) let namespaceName = "\(Constants.ServerURL.serverNamespacePrefix)\(index + 1)" - let typeName = TypeName(swiftKeyPath: [Constants.ServerURL.namespace, namespaceName, Constants.ServerURL.urlStaticFunc]) + let typeName = TypeName(swiftKeyPath: [ + Constants.ServerURL.namespace, namespaceName, Constants.ServerURL.urlStaticFunc, + ]) let decl = Declaration.commentable( server.description.map(Comment.doc(_:)), .enum( @@ -137,15 +146,17 @@ extension TypesFileTranslator { /// - Returns: A declaration of an enum namespace of the server URLs type. func translateServers(_ servers: [OpenAPI.Server]) -> Declaration { var serverDecls: [Declaration] = [] - for (index, server) in servers.enumerated() { let translatedServer = translateServer(index: index, server: server) serverDecls.append(contentsOf: [ translatedServer.decl, - translateServerAsDeprecated(index: index, server: server, renamedTo: translatedServer.pathToStaticFunction) + translateServerAsDeprecated( + index: index, + server: server, + renamedTo: translatedServer.pathToStaticFunction + ), ]) } - return .commentable( .doc("Server URLs defined in the OpenAPI document."), .enum(accessModifier: config.access, name: Constants.ServerURL.namespace, members: serverDecls) diff --git a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift index 42d52df5..c8b96ff0 100644 --- a/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift +++ b/Sources/_OpenAPIGeneratorCore/Translator/TypesTranslator/translateServersVariables.swift @@ -13,6 +13,25 @@ //===----------------------------------------------------------------------===// import OpenAPIKit +/// Represents a server variable and the function of generation that should be applied. +protocol ServerVariableGenerator { + /// Returns the declaration (enum) that should be added to the server's namespace. + /// If the server variable does not require any codegen then it should return `nil`. + var declaration: Declaration? { get } + + /// Returns the description of the parameter that will be used to define the variable + /// in the static method for a given server. + var parameter: ParameterDescription { get } + + /// Returns an expression for the variable initializer that is used in the body of a server's + /// static method by passing it along to the URL resolver. + var initializer: Expression { get } + + /// Returns the description of this variables documentation for the function comment of + /// the server's static method. + var functionComment: (name: String, comment: String?) { get } +} + extension TypesFileTranslator { /// Returns a declaration of a namespace (enum) for a specific server and will define /// one enum member for each of the server's variables in the OpenAPI Document. @@ -25,16 +44,13 @@ extension TypesFileTranslator { /// only `RawStringTranslatedServerVariable` generators will be returned. /// - Returns: A declaration of the server variables namespace, or `nil` if no /// variables are declared. - func translateServerVariables(index: Int, server: OpenAPI.Server, generateAsEnum: Bool) -> [any ServerVariableGenerator] { - return server.variables.map { key, variable in + func translateServerVariables(index: Int, server: OpenAPI.Server, generateAsEnum: Bool) + -> [any ServerVariableGenerator] + { + server.variables.map { key, variable in guard generateAsEnum, let enumValues = variable.enum else { - return RawStringTranslatedServerVariable( - key: key, - variable: variable, - context: context - ) + return RawStringTranslatedServerVariable(key: key, variable: variable, context: context) } - return GeneratedEnumTranslatedServerVariable( key: key, variable: variable, @@ -46,26 +62,7 @@ extension TypesFileTranslator { } // MARK: Generators - - /// Represents a server variable and the function of generation that should be applied. - protocol ServerVariableGenerator { - /// Returns the declaration (enum) that should be added to the server's namespace. - /// If the server variable does not require any codegen then it should return `nil`. - var declaration: Declaration? { get } - - /// Returns the description of the parameter that will be used to define the variable - /// in the static method for a given server. - var parameter: ParameterDescription { get } - - /// Returns an expression for the variable initializer that is used in the body of a server's - /// static method by passing it along to the URL resolver. - var initializer: Expression { get } - /// Returns the description of this variables documentation for the function comment of - /// the server's static method. - var functionComment: (name: String, comment: String?) { get } - } - /// Represents a variable that is required to be represented as a `Swift.String`. private struct RawStringTranslatedServerVariable: ServerVariableGenerator { /// The key of the variable defined in the Open API document. @@ -96,17 +93,13 @@ extension TypesFileTranslator { var declaration: Declaration? { // A variable being represented by a `Swift.String` does not have a declaration that needs to // be added to the server's namespace. - return nil + nil } /// Returns the description of the parameter that will be used to define the variable /// in the static method for a given server. var parameter: ParameterDescription { - return .init( - label: swiftSafeKey, - type: .init(TypeName.string), - defaultValue: .literal(variable.default) - ) + .init(label: swiftSafeKey, type: .init(TypeName.string), defaultValue: .literal(variable.default)) } /// Returns an expression for the variable initializer that is used in the body of a server's @@ -117,19 +110,16 @@ extension TypesFileTranslator { .init(label: "value", expression: .identifierPattern(swiftSafeKey)), ] if let allowedValues = variable.enum { - arguments.append(.init( - label: "allowedValues", - expression: .literal(.array(allowedValues.map { .literal($0) })) - )) + arguments.append( + .init(label: "allowedValues", expression: .literal(.array(allowedValues.map { .literal($0) }))) + ) } return .dot("init").call(arguments) } /// Returns the description of this variables documentation for the function comment of /// the server's static method. - var functionComment: (name: String, comment: String?) { - (name: swiftSafeKey, comment: variable.description) - } + var functionComment: (name: String, comment: String?) { (name: swiftSafeKey, comment: variable.description) } } /// Represents an Open API "Server Variable Object" that will be generated as an enum and added @@ -166,13 +156,18 @@ extension TypesFileTranslator { /// - accessModifier: The access modifier to use for generated declarations. /// - context: The translator context the generator should use to create /// Swift safe identifiers. - init(key: String, variable: OpenAPI.Server.Variable, enumValues: [String], accessModifier: AccessModifier, context: TranslatorContext) { + init( + key: String, + variable: OpenAPI.Server.Variable, + enumValues: [String], + accessModifier: AccessModifier, + context: TranslatorContext + ) { self.key = key swiftSafeKey = context.asSwiftSafeName(key) enumName = context.asSwiftSafeName(key.localizedCapitalized) self.variable = variable self.enumValues = enumValues - self.context = context self.accessModifier = accessModifier } @@ -180,16 +175,14 @@ extension TypesFileTranslator { /// Returns the declaration (enum) that should be added to the server's namespace. /// If the server variable does not require any codegen then it should return `nil`. var declaration: Declaration? { - let description: String = if let description = variable.description { - description + "\n\n" - } else { - "" - } + let description: String = if let description = variable.description { description + "\n\n" } else { "" } return .commentable( - .doc(""" - \(description)The "\(key)" variable defined in the OpenAPI document. The default value is "\(variable.default)". - """), + .doc( + """ + \(description)The "\(key)" variable defined in the OpenAPI document. The default value is "\(variable.default)". + """ + ), .enum( isFrozen: true, accessModifier: accessModifier, @@ -203,7 +196,7 @@ extension TypesFileTranslator { /// Returns the description of the parameter that will be used to define the variable /// in the static method for a given server. var parameter: ParameterDescription { - return .init( + .init( label: swiftSafeKey, type: .member([enumName]), defaultValue: .memberAccess(.dot(context.asSwiftSafeName(variable.default))) @@ -213,22 +206,19 @@ extension TypesFileTranslator { /// Returns an expression for the variable initializer that is used in the body of a server's /// static method by passing it along to the URL resolver. var initializer: Expression { - .dot("init").call( - [ + .dot("init") + .call([ .init(label: "name", expression: .literal(key)), - .init(label: "value", expression: .memberAccess(.init( - left: .identifierPattern(swiftSafeKey), - right: "rawValue" - ))), - ] - ) + .init( + label: "value", + expression: .memberAccess(.init(left: .identifierPattern(swiftSafeKey), right: "rawValue")) + ), + ]) } /// Returns the description of this variables documentation for the function comment of /// the server's static method. - var functionComment: (name: String, comment: String?) { - (name: swiftSafeKey, comment: variable.description) - } + var functionComment: (name: String, comment: String?) { (name: swiftSafeKey, comment: variable.description) } /// Returns an enum case declaration for a raw string enum. /// diff --git a/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift b/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift index 9775d0fe..ba5e5905 100644 --- a/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift +++ b/Tests/OpenAPIGeneratorReferenceTests/SnippetBasedReferenceTests.swift @@ -5497,14 +5497,13 @@ extension SnippetBasedReferenceTests { components: components ) } - func makeTypesTranslator( accessModifier: AccessModifier = .public, featureFlags: FeatureFlags = [], ignoredDiagnosticMessages: Set = [], components: OpenAPI.Components = .noComponents ) throws -> TypesFileTranslator { - return TypesFileTranslator( + TypesFileTranslator( config: Config(mode: .types, access: accessModifier, featureFlags: featureFlags), diagnostics: XCTestDiagnosticCollector(test: self, ignoredDiagnosticMessages: ignoredDiagnosticMessages), components: components