@@ -1,6 +1,6 @@
1+{-# LANGUAGE CPP #-}
12{-# LANGUAGE DataKinds #-}
23{-# LANGUAGE DeriveDataTypeable #-}
3−{-# LANGUAGE DeriveFunctor #-}
44{-# LANGUAGE DeriveGeneric #-}
55{-# LANGUAGE DeriveTraversable #-}
66{-# LANGUAGE FlexibleContexts #-}
@@ -14,87 +14,91 @@
1414{-# LANGUAGE TemplateHaskell #-}
1515{-# LANGUAGE TypeFamilies #-}
1616{-# LANGUAGE UndecidableInstances #-}
17−module Data.Swagger.Internal where
17+module Data.OpenApi.Internal where
1818
1919import Prelude ()
2020import Prelude.Compat
2121
22−import Control.Lens ((&), (.~), (?~))
2322import Control.Applicative
24−import Data.Aeson hiding (Encoding)
25−import qualified Data.Aeson.Types as JSON
26−import Data.Data (Data(..), Typeable, mkConstr, mkDataType, Fixity(..), Constr, DataType, constrIndex)
27−import Data.Hashable (Hashable)
28−import qualified Data.HashMap.Strict as HashMap
29−import Data.HashSet.InsOrd (InsOrdHashSet)
30−import Data.Map (Map)
31−import qualified Data.Map as Map
32−import Data.Monoid (Monoid (..))
33−import Data.Semigroup.Compat (Semigroup (..))
34−import Data.Scientific (Scientific)
35−import Data.String (IsString(..))
36−import Data.Text (Text)
37−import qualified Data.Text as Text
38−import GHC.Generics (Generic)
39−import Network.Socket (HostName, PortNumber)
40−import Network.HTTP.Media (MediaType)
41−import Text.Read (readMaybe)
23+import Control.Lens ((&), (.~), (?~))
24+import Data.Aeson hiding (Encoding)
25+#if MIN_VERSION_aeson(2,0,0)
26+import qualified Data.Aeson.KeyMap as KeyMap
27+#endif
28+import qualified Data.Aeson.Types as JSON
29+import Data.Data (Constr, Data (..), DataType, Fixity (..), Typeable,
30+ constrIndex, mkConstr, mkDataType)
31+import Data.Hashable (Hashable (..))
32+import qualified Data.HashMap.Strict as HashMap
33+import Data.HashSet.InsOrd (InsOrdHashSet)
34+import Data.Map (Map)
35+import qualified Data.Map as Map
36+import Data.Monoid (Monoid (..))
37+import Data.Scientific (Scientific)
38+import Data.Semigroup.Compat (Semigroup (..))
39+import Data.String (IsString (..))
40+import Data.Text (Text)
41+import qualified Data.Text as Text
42+import Data.Text.Encoding (encodeUtf8)
43+import GHC.Generics (Generic)
44+import Network.HTTP.Media (MediaType, mainType, parameters, parseAccept, subType, (//),
45+ (/:))
46+import Network.Socket (HostName, PortNumber)
47+import Text.Read (readMaybe)
4248
4349import Data.HashMap.Strict.InsOrd (InsOrdHashMap)
4450import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
4551
52+import Data.OpenApi.Aeson.Compat (deleteKey)
53+import Data.OpenApi.Internal.AesonUtils (AesonDefaultValue (..), HasSwaggerAesonOptions (..),
54+ mkSwaggerAesonOptions, saoAdditionalPairs, saoSubObject,
55+ sopSwaggerGenericParseJSON, sopSwaggerGenericToEncoding,
56+ sopSwaggerGenericToJSON, sopSwaggerGenericToJSONWithOpts)
57+import Data.OpenApi.Internal.Utils
4658import Generics.SOP.TH (deriveGeneric)
47−import Data.Swagger.Internal.AesonUtils (sopSwaggerGenericToJSON
48− ,sopSwaggerGenericToJSONWithOpts
49− ,sopSwaggerGenericParseJSON
50− ,HasSwaggerAesonOptions(..)
51− ,AesonDefaultValue(..)
52− ,mkSwaggerAesonOptions
53− ,saoAdditionalPairs
54− ,saoSubObject)
55−import Data.Swagger.Internal.Utils
56−import Data.Swagger.Internal.AesonUtils (sopSwaggerGenericToEncoding)
5759
5860-- $setup
5961-- >>> :seti -XDataKinds
6062-- >>> import Data.Aeson
63+-- >>> import Data.ByteString.Lazy.Char8 as BSL
64+-- >>> import Data.OpenApi.Internal.Utils
6165
6266-- | A list of definitions that can be used in references.
6367type Definitions = InsOrdHashMap Text
6468
6569-- | This is the root document object for the API specification.
66−data Swagger = Swagger
70+data OpenApi = OpenApi
6771 { -- | Provides metadata about the API.
6872 -- The metadata can be used by the clients if needed.
69− _swaggerInfo :: Info
73+ _openApiInfo :: Info
7074
7175 -- | An array of Server Objects, which provide connectivity information
7276 -- to a target server. If the servers property is not provided, or is an empty array,
7377 -- the default value would be a 'Server' object with a url value of @/@.
74− , _swaggerServers :: [Server]
78+ , _openApiServers :: [Server]
7579
7680 -- | The available paths and operations for the API.
77− , _swaggerPaths :: InsOrdHashMap FilePath PathItem
81+ , _openApiPaths :: InsOrdHashMap FilePath PathItem
7882
7983 -- | An element to hold various schemas for the specification.
80− , _swaggerComponents :: Components
84+ , _openApiComponents :: Components
8185
8286 -- | A declaration of which security mechanisms can be used across the API.
8387 -- The list of values includes alternative security requirement objects that can be used.
8488 -- Only one of the security requirement objects need to be satisfied to authorize a request.
8589 -- Individual operations can override this definition.
8690 -- To make security optional, an empty security requirement can be included in the array.
87− , _swaggerSecurity :: [SecurityRequirement]
91+ , _openApiSecurity :: [SecurityRequirement]
8892
8993 -- | A list of tags used by the specification with additional metadata.
9094 -- The order of the tags can be used to reflect on their order by the parsing tools.
9195 -- Not all tags that are used by the 'Operation' Object must be declared.
9296 -- The tags that are not declared MAY be organized randomly or based on the tools' logic.
9397 -- Each tag name in the list MUST be unique.
94− , _swaggerTags :: InsOrdHashSet Tag
98+ , _openApiTags :: InsOrdHashSet Tag
9599
96100 -- | Additional external documentation.
97− , _swaggerExternalDocs :: Maybe ExternalDocs
101+ , _openApiExternalDocs :: Maybe ExternalDocs
98102 } deriving (Eq, Show, Generic, Data, Typeable)
99103
100104-- | The object provides metadata about the API.
@@ -191,10 +195,10 @@ data Components = Components
191195 , _componentsParameters :: Definitions Param
192196 , _componentsExamples :: Definitions Example
193197 , _componentsRequestBodies :: Definitions RequestBody
194− , _componentsHeader :: Definitions Header
195− , _componentsSecuritySchemes :: Definitions SecurityScheme
196−-- , _componentsLinks
197−-- , _componentsCallbacks
198+ , _componentsHeaders :: Definitions Header
199+ , _componentsSecuritySchemes :: SecurityDefinitions
200+ , _componentsLinks :: Definitions Link
201+ , _componentsCallbacks :: Definitions Callback
198202 } deriving (Eq, Show, Generic, Data, Typeable)
199203
200204-- | Describes the operations available on a single path.
@@ -284,7 +288,11 @@ data Operation = Operation
284288 -- | The list of possible responses as they are returned from executing this operation.
285289 , _operationResponses :: Responses
286290
287− -- TODO callbacks
291+ -- | A map of possible out-of band callbacks related to the parent operation.
292+ -- The key is a unique identifier for the 'Callback' Object.
293+ -- Each value in the map is a 'Callback' Object that describes a request
294+ -- that may be initiated by the API provider and the expected responses.
295+ , _operationCallbacks :: InsOrdHashMap Text (Referenced Callback)
288296
289297 -- | Declares this operation to be deprecated.
290298 -- Usage of the declared operation should be refrained.
@@ -304,6 +312,22 @@ data Operation = Operation
304312 , _operationServers :: [Server]
305313 } deriving (Eq, Show, Generic, Data, Typeable)
306314
315+-- This instance should be in @http-media@.
316+instance Data MediaType where
317+ gunfold k z c = case constrIndex c of
318+ 1 -> k (k (k (z (\main sub params -> foldl (/:) (main // sub) (Map.toList params)))))
319+ _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type MediaType."
320+
321+ toConstr _ = mediaTypeConstr
322+
323+ dataTypeOf _ = mediaTypeData
324+
325+mediaTypeConstr = mkConstr mediaTypeData "MediaType" [] Prefix
326+mediaTypeData = mkDataType "MediaType" [mediaTypeConstr]
327+
328+instance Hashable MediaType where
329+ hashWithSalt salt mt = salt `hashWithSalt` show mt
330+
307331-- | Describes a single request body.
308332data RequestBody = RequestBody
309333 { -- | A brief description of the request body. This could contain examples of use.
@@ -313,9 +337,11 @@ data RequestBody = RequestBody
313337 -- | The content of the request body.
314338 -- The key is a media type or media type range and the value describes it.
315339 -- For requests that match multiple keys, only the most specific key is applicable.
316− -- e.g. @text/plain@ overrides @text/*@
317− , _requestBodyContent :: InsOrdHashMap {-MediaType-} Text MediaTypeObject -- FIXME Data MediaType
340+ -- e.g. @text/plain@ overrides @text/\*@
341+ , _requestBodyContent :: InsOrdHashMap MediaType MediaTypeObject
318342
343+ -- | Determines if the request body is required in the request.
344+ -- Defaults to 'False'.
319345 , _requestBodyRequired :: Maybe Bool
320346 } deriving (Eq, Show, Generic, Data, Typeable)
321347
@@ -368,8 +394,8 @@ data Encoding = Encoding
368394 -- for other primitive types – @text/plain@; for object - @application/json@;
369395 -- for array – the default is defined based on the inner type.
370396 -- The value can be a specific media type (e.g. @application/json@),
371− -- a wildcard media type (e.g. @image/*@), or a comma-separated list of the two types.
372− _encodingContentType :: Maybe Text
397+ -- a wildcard media type (e.g. @image/\*@), or a comma-separated list of the two types.
398+ _encodingContentType :: Maybe MediaType
373399
374400 -- | A map allowing additional information to be provided as headers,
375401 -- for example @Content-Disposition@. @Content-Type@ is described separately
@@ -408,18 +434,15 @@ mimeListConstr :: Constr
408434mimeListConstr = mkConstr mimeListDataType "MimeList" ["getMimeList"] Prefix
409435
410436mimeListDataType :: DataType
411−mimeListDataType = mkDataType "Data.Swagger.MimeList" [mimeListConstr]
437+mimeListDataType = mkDataType "Data.OpenApi.MimeList" [mimeListConstr]
412438
413439instance Data MimeList where
414440 gunfold k z c = case constrIndex c of
415− 1 -> k (z (\xs -> MimeList (map fromString xs)))
441+ 1 -> k (z (MimeList . map fromString))
416442 _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type MimeList."
417443 toConstr (MimeList _) = mimeListConstr
418444 dataTypeOf _ = mimeListDataType
419445
420−-- TODO style
421−-- TODO example
422−
423446-- | Describes a single operation parameter.
424447-- A unique parameter is defined by a combination of a name and location.
425448data Param = Param
@@ -429,7 +452,7 @@ data Param = Param
429452
430453 -- | A brief description of the parameter.
431454 -- This could contain examples of use.
432− -- GFM syntax can be used for rich text representation.
455+ -- CommonMark syntax MAY be used for rich text representation.
433456 , _paramDescription :: Maybe Text
434457
435458 -- | Determines whether this parameter is mandatory.
@@ -449,6 +472,13 @@ data Param = Param
449472 -- a parameter with an empty value. Default value is @false@.
450473 , _paramAllowEmptyValue :: Maybe Bool
451474
475+ -- | Determines whether the parameter value SHOULD allow reserved characters,
476+ -- as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2)
477+ -- @:/?#[]@!$&'()*+,;=@ to be included without percent-encoding.
478+ -- This property only applies to parameters with an '_paramIn' value of 'ParamQuery'.
479+ -- The default value is 'False'.
480+ , _paramAllowReserved :: Maybe Bool
481+
452482 -- | Parameter schema.
453483 , _paramSchema :: Maybe (Referenced Schema)
454484
@@ -479,6 +509,10 @@ data Param = Param
479509 -- Furthermore, if referencing a schema that contains an example,
480510 -- the examples value SHALL override the example provided by the schema.
481511 , _paramExamples :: InsOrdHashMap Text (Referenced Example)
512+
513+ -- TODO
514+ -- _paramContent :: InsOrdHashMap MediaType MediaTypeObject
515+ -- should be singleton. mutually exclusive with _paramSchema.
482516 } deriving (Eq, Show, Generic, Data, Typeable)
483517
484518data Example = Example
@@ -503,27 +537,63 @@ data Example = Example
503537 , _exampleExternalValue :: Maybe URL
504538 } deriving (Eq, Show, Generic, Typeable, Data)
505539
506−-- | Items for @'SwaggerArray'@ schemas.
540+data ExpressionOrValue
541+ = Expression Text
542+ | Value Value
543+ deriving (Eq, Show, Generic, Typeable, Data)
544+
545+-- | The Link object represents a possible design-time link for a response.
546+-- The presence of a link does not guarantee the caller's ability to successfully invoke it,
547+-- rather it provides a known relationship and traversal mechanism between responses and other operations.
548+data Link = Link
549+ { -- | A relative or absolute URI reference to an OAS operation.
550+ -- This field is mutually exclusive of the '_linkOperationId' field,
551+ -- and MUST point to an 'Operation' Object. Relative '_linkOperationRef'
552+ -- values MAY be used to locate an existing 'Operation' Object in the OpenAPI definition.
553+ _linkOperationRef :: Maybe Text
554+
555+ -- | The name of an /existing/, resolvable OAS operation, as defined with a unique
556+ -- '_operationOperationId'. This field is mutually exclusive of the '_linkOperationRef' field.
557+ , _linkOperationId :: Maybe Text
558+
559+ -- | A map representing parameters to pass to an operation as specified with '_linkOperationId'
560+ -- or identified via '_linkOperationRef'. The key is the parameter name to be used, whereas
561+ -- the value can be a constant or an expression to be evaluated and passed to the linked operation.
562+ -- The parameter name can be qualified using the parameter location @[{in}.]{name}@
563+ -- for operations that use the same parameter name in different locations (e.g. path.id).
564+ , _linkParameters :: InsOrdHashMap Text ExpressionOrValue
565+
566+ -- | A literal value or @{expression}@ to use as a request body when calling the target operation.
567+ , _linkRequestBody :: Maybe ExpressionOrValue
568+
569+ -- | A description of the link.
570+ , _linkDescription :: Maybe Text
571+
572+ -- | A server object to be used by the target operation.
573+ , _linkServer :: Maybe Server
574+ } deriving (Eq, Show, Generic, Typeable, Data)
575+
576+-- | Items for @'OpenApiArray'@ schemas.
507577--
508578-- __Warning__: OpenAPI 3.0 does not support tuple arrays. However, OpenAPI 3.1 will, as
509579-- it will incorporate Json Schema mostly verbatim.
510580--
511−-- @'SwaggerItemsObject'@ should be used to specify homogenous array @'Schema'@s.
581+-- @'OpenApiItemsObject'@ should be used to specify homogenous array @'Schema'@s.
512582--
513−-- @'SwaggerItemsArray'@ should be used to specify tuple @'Schema'@s.
514−data SwaggerItems where
515− SwaggerItemsObject :: Referenced Schema -> SwaggerItems
516− SwaggerItemsArray :: [Referenced Schema] -> SwaggerItems
583+-- @'OpenApiItemsArray'@ should be used to specify tuple @'Schema'@s.
584+data OpenApiItems where
585+ OpenApiItemsObject :: Referenced Schema -> OpenApiItems
586+ OpenApiItemsArray :: [Referenced Schema] -> OpenApiItems
517587 deriving (Eq, Show, Typeable, Data)
518588
519−data SwaggerType where
520− SwaggerString :: SwaggerType
521− SwaggerNumber :: SwaggerType
522− SwaggerInteger :: SwaggerType
523− SwaggerBoolean :: SwaggerType
524− SwaggerArray :: SwaggerType
525− SwaggerNull :: SwaggerType
526− SwaggerObject :: SwaggerType
589+data OpenApiType where
590+ OpenApiString :: OpenApiType
591+ OpenApiNumber :: OpenApiType
592+ OpenApiInteger :: OpenApiType
593+ OpenApiBoolean :: OpenApiType
594+ OpenApiArray :: OpenApiType
595+ OpenApiNull :: OpenApiType
596+ OpenApiObject :: OpenApiType
527597 deriving (Eq, Show, Typeable, Generic, Data)
528598
529599data ParamLocation
@@ -568,9 +638,33 @@ data Schema = Schema
568638 , _schemaMaxProperties :: Maybe Integer
569639 , _schemaMinProperties :: Maybe Integer
570640
571− , _schemaParamSchema :: ParamSchema
641+ , -- | Declares the value of the parameter that the server will use if none is provided,
642+ -- for example a @"count"@ to control the number of results per page might default to @100@
643+ -- if not supplied by the client in the request.
644+ -- (Note: "default" has no meaning for required parameters.)
645+ -- Unlike JSON Schema this value MUST conform to the defined type for this parameter.
646+ _schemaDefault :: Maybe Value
647+
648+ , _schemaType :: Maybe OpenApiType
649+ , _schemaFormat :: Maybe Format
650+ , _schemaItems :: Maybe OpenApiItems
651+ , _schemaMaximum :: Maybe Scientific
652+ , _schemaExclusiveMaximum :: Maybe Bool
653+ , _schemaMinimum :: Maybe Scientific
654+ , _schemaExclusiveMinimum :: Maybe Bool
655+ , _schemaMaxLength :: Maybe Integer
656+ , _schemaMinLength :: Maybe Integer
657+ , _schemaPattern :: Maybe Pattern
658+ , _schemaMaxItems :: Maybe Integer
659+ , _schemaMinItems :: Maybe Integer
660+ , _schemaUniqueItems :: Maybe Bool
661+ , _schemaEnum :: Maybe [Value]
662+ , _schemaMultipleOf :: Maybe Scientific
572663 } deriving (Eq, Show, Generic, Data, Typeable)
573664
665+-- | Regex pattern for @string@ type.
666+type Pattern = Text
667+
574668data Discriminator = Discriminator
575669 { -- | The name of the property in the payload that will hold the discriminator value.
576670 _discriminatorPropertyName :: Text
@@ -586,37 +680,9 @@ data NamedSchema = NamedSchema
586680 , _namedSchemaSchema :: Schema
587681 } deriving (Eq, Show, Generic, Data, Typeable)
588682
589−-- | Regex pattern for @string@ type.
590−type Pattern = Text
591−
592−data ParamSchema = ParamSchema
593− { -- | Declares the value of the parameter that the server will use if none is provided,
594− -- for example a @"count"@ to control the number of results per page might default to @100@
595− -- if not supplied by the client in the request.
596− -- (Note: "default" has no meaning for required parameters.)
597− -- Unlike JSON Schema this value MUST conform to the defined type for this parameter.
598− _paramSchemaDefault :: Maybe Value
599−
600− , _paramSchemaType :: Maybe SwaggerType
601− , _paramSchemaFormat :: Maybe Format
602− , _paramSchemaItems :: Maybe SwaggerItems
603− , _paramSchemaMaximum :: Maybe Scientific
604− , _paramSchemaExclusiveMaximum :: Maybe Bool
605− , _paramSchemaMinimum :: Maybe Scientific
606− , _paramSchemaExclusiveMinimum :: Maybe Bool
607− , _paramSchemaMaxLength :: Maybe Integer
608− , _paramSchemaMinLength :: Maybe Integer
609− , _paramSchemaPattern :: Maybe Pattern
610− , _paramSchemaMaxItems :: Maybe Integer
611− , _paramSchemaMinItems :: Maybe Integer
612− , _paramSchemaUniqueItems :: Maybe Bool
613− , _paramSchemaEnum :: Maybe [Value]
614− , _paramSchemaMultipleOf :: Maybe Scientific
615− } deriving (Eq, Show, Generic, Typeable, Data)
616−
617683data Xml = Xml
618684 { -- | Replaces the name of the element/attribute used for the described schema property.
619− -- When defined within the @'SwaggerItems'@ (items), it will affect the name of the individual XML elements within the list.
685+ -- When defined within the @'OpenApiItems'@ (items), it will affect the name of the individual XML elements within the list.
620686 -- When defined alongside type being array (outside the items),
621687 -- it will affect the wrapping element and only if wrapped is true.
622688 -- If wrapped is false, it will be ignored.
@@ -668,25 +734,44 @@ data Response = Response
668734 -- | A map containing descriptions of potential response payloads.
669735 -- The key is a media type or media type range and the value describes it.
670736 -- For responses that match multiple keys, only the most specific key is applicable.
671− -- e.g. @text/plain@ overrides @text/*@.
672− , _responseContent :: InsOrdHashMap Text MediaTypeObject
737+ -- e.g. @text/plain@ overrides @text/\*@.
738+ , _responseContent :: InsOrdHashMap MediaType MediaTypeObject
673739
674740 -- | Maps a header name to its definition.
675741 , _responseHeaders :: InsOrdHashMap HeaderName (Referenced Header)
676742
677− -- TODO links
743+ -- | A map of operations links that can be followed from the response.
744+ -- The key of the map is a short name for the link, following the naming
745+ -- constraints of the names for 'Component' Objects.
746+ , _responseLinks :: InsOrdHashMap Text (Referenced Link)
678747 } deriving (Eq, Show, Generic, Data, Typeable)
679748
680749instance IsString Response where
681− fromString s = Response (fromString s) mempty mempty
750+ fromString s = Response (fromString s) mempty mempty mempty
751+
752+-- | A map of possible out-of band callbacks related to the parent operation.
753+-- Each value in the map is a 'PathItem' Object that describes a set of requests that
754+-- may be initiated by the API provider and the expected responses.
755+-- The key value used to identify the path item object is an expression, evaluated at runtime,
756+-- that identifies a URL to use for the callback operation.
757+newtype Callback = Callback (InsOrdHashMap Text PathItem)
758+ deriving (Eq, Show, Generic, Data, Typeable)
682759
683760type HeaderName = Text
684761
685−
686−-- TODO this is mostly a copy of 'Param'.
762+-- | Header fields have the same meaning as for 'Param'.
763+--
764+-- Style is always treated as 'StyleSimple', as it is the only value allowed for headers.
687765data Header = Header
688766 { -- | A short description of the header.
689− _headerDescription :: Maybe Text
767+ _headerDescription :: Maybe HeaderName
768+
769+ , _headerRequired :: Maybe Bool
770+ , _headerDeprecated :: Maybe Bool
771+ , _headerAllowEmptyValue :: Maybe Bool
772+ , _headerExplode :: Maybe Bool
773+ , _headerExample :: Maybe Value
774+ , _headerExamples :: InsOrdHashMap Text (Referenced Example)
690775
691776 , _headerSchema :: Maybe (Referenced Schema)
692777 } deriving (Eq, Show, Generic, Data, Typeable)
@@ -712,17 +797,17 @@ type AuthorizationURL = Text
712797-- | The token URL to be used for OAuth2 flow. This SHOULD be in the form of a URL.
713798type TokenURL = Text
714799
715−data OAuth2ImplicitFlow = OAuth2ImplicitFlow
716− { _oAuth2ImplicitFlowAuthorizationUrl :: AuthorizationURL
717− } deriving (Eq, Show, Generic, Data, Typeable)
800+newtype OAuth2ImplicitFlow
801+ = OAuth2ImplicitFlow {_oAuth2ImplicitFlowAuthorizationUrl :: AuthorizationURL}
802+ deriving (Eq, Show, Generic, Data, Typeable)
718803
719−data OAuth2PasswordFlow = OAuth2PasswordFlow
720− { _oAuth2PasswordFlowTokenUrl :: TokenURL
721− } deriving (Eq, Show, Generic, Data, Typeable)
804+newtype OAuth2PasswordFlow
805+ = OAuth2PasswordFlow {_oAuth2PasswordFlowTokenUrl :: TokenURL}
806+ deriving (Eq, Show, Generic, Data, Typeable)
722807
723−data OAuth2ClientCredentialsFlow = OAuth2ClientCredentialsFlow
724− { _oAuth2ClientCredentialsFlowTokenUrl :: TokenURL
725− } deriving (Eq, Show, Generic, Data, Typeable)
808+newtype OAuth2ClientCredentialsFlow
809+ = OAuth2ClientCredentialsFlow {_oAuth2ClientCredentialsFlowTokenUrl :: TokenURL}
810+ deriving (Eq, Show, Generic, Data, Typeable)
726811
727812data OAuth2AuthorizationCodeFlow = OAuth2AuthorizationCodeFlow
728813 { _oAuth2AuthorizationCodeFlowAuthorizationUrl :: AuthorizationURL
@@ -755,8 +840,50 @@ data OAuth2Flows = OAuth2Flows
755840 , _oAuth2FlowsAuthorizationCode :: Maybe (OAuth2Flow OAuth2AuthorizationCodeFlow)
756841 } deriving (Eq, Show, Generic, Data, Typeable)
757842
843+type BearerFormat = Text
844+
845+data HttpSchemeType
846+ = HttpSchemeBearer (Maybe BearerFormat)
847+ | HttpSchemeBasic
848+ | HttpSchemeCustom Text
849+ deriving (Eq, Show, Generic, Data, Typeable)
850+
851+-- |
852+--
853+-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeHttp (HttpSchemeBearer Nothing))
854+-- {
855+-- "scheme": "bearer",
856+-- "type": "http"
857+-- }
858+--
859+-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeHttp (HttpSchemeBearer (Just "jwt")))
860+-- {
861+-- "bearerFormat": "jwt",
862+-- "scheme": "bearer",
863+-- "type": "http"
864+-- }
865+--
866+-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeHttp HttpSchemeBasic)
867+-- {
868+-- "scheme": "basic",
869+-- "type": "http"
870+-- }
871+--
872+-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeHttp (HttpSchemeCustom "CANARY"))
873+-- {
874+-- "scheme": "CANARY",
875+-- "type": "http"
876+-- }
877+--
878+-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeApiKey (ApiKeyParams "id" ApiKeyCookie))
879+-- {
880+-- "in": "cookie",
881+-- "name": "id",
882+-- "type": "apiKey"
883+-- }
884+--
758885data SecuritySchemeType
759− = SecuritySchemeHttp
886+ = SecuritySchemeHttp HttpSchemeType
760887 | SecuritySchemeApiKey ApiKeyParams
761888 | SecuritySchemeOAuth2 OAuth2Flows
762889 | SecuritySchemeOpenIdConnect URL
@@ -791,7 +918,7 @@ data Tag = Tag
791918 _tagName :: TagName
792919
793920 -- | A short description for the tag.
794− -- GFM syntax can be used for rich text representation.
921+ -- [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation.
795922 , _tagDescription :: Maybe Text
796923
797924 -- | Additional external documentation for this tag.
@@ -806,7 +933,7 @@ instance IsString Tag where
806933-- | Allows referencing an external resource for extended documentation.
807934data ExternalDocs = ExternalDocs
808935 { -- | A short description of the target documentation.
809− -- GFM syntax can be used for rich text representation.
936+ -- [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation.
810937 _externalDocsDescription :: Maybe Text
811938
812939 -- | The URL for the target documentation.
@@ -853,18 +980,18 @@ deriveGeneric ''MediaTypeObject
853980deriveGeneric ''Responses
854981deriveGeneric ''SecurityScheme
855982deriveGeneric ''Schema
856−deriveGeneric ''ParamSchema
857−deriveGeneric ''Swagger
983+deriveGeneric ''OpenApi
858984deriveGeneric ''Example
859985deriveGeneric ''Encoding
986+deriveGeneric ''Link
860987
861988-- =======================================================================
862989-- Monoid instances
863990-- =======================================================================
864991
865−instance Semigroup Swagger where
992+instance Semigroup OpenApi where
866993 (<>) = genericMappend
867−instance Monoid Swagger where
994+instance Monoid OpenApi where
868995 mempty = genericMempty
869996 mappend = (<>)
870997
@@ -898,12 +1025,6 @@ instance Monoid Schema where
8981025 mempty = genericMempty
8991026 mappend = (<>)
9001027
901−instance Semigroup ParamSchema where
902− (<>) = genericMappend
903−instance Monoid ParamSchema where
904− mempty = genericMempty
905− mappend = (<>)
906−
9071028instance Semigroup Param where
9081029 (<>) = genericMappend
9091030instance Monoid Param where
@@ -998,19 +1119,19 @@ instance SwaggerMonoid Info
9981119instance SwaggerMonoid Components
9991120instance SwaggerMonoid PathItem
10001121instance SwaggerMonoid Schema
1001−instance SwaggerMonoid ParamSchema
10021122instance SwaggerMonoid Param
10031123instance SwaggerMonoid Responses
10041124instance SwaggerMonoid Response
10051125instance SwaggerMonoid ExternalDocs
10061126instance SwaggerMonoid Operation
10071127instance (Eq a, Hashable a) => SwaggerMonoid (InsOrdHashSet a)
1128+instance SwaggerMonoid SecurityDefinitions
10081129
10091130instance SwaggerMonoid MimeList
10101131deriving instance SwaggerMonoid URL
10111132
1012−instance SwaggerMonoid SwaggerType where
1013− swaggerMempty = SwaggerString
1133+instance SwaggerMonoid OpenApiType where
1134+ swaggerMempty = OpenApiString
10141135 swaggerMappend _ y = y
10151136
10161137instance SwaggerMonoid ParamLocation where
@@ -1033,7 +1154,7 @@ instance Monoid a => SwaggerMonoid (Referenced a) where
10331154instance ToJSON Style where
10341155 toJSON = genericToJSON (jsonPrefix "Style")
10351156
1036−instance ToJSON SwaggerType where
1157+instance ToJSON OpenApiType where
10371158 toJSON = genericToJSON (jsonPrefix "Swagger")
10381159
10391160instance ToJSON ParamLocation where
@@ -1088,7 +1209,7 @@ instance ToJSON OAuth2AuthorizationCodeFlow where
10881209instance FromJSON Style where
10891210 parseJSON = genericParseJSON (jsonPrefix "Style")
10901211
1091−instance FromJSON SwaggerType where
1212+instance FromJSON OpenApiType where
10921213 parseJSON = genericParseJSON (jsonPrefix "Swagger")
10931214
10941215instance FromJSON ParamLocation where
@@ -1137,7 +1258,14 @@ instance FromJSON OAuth2AuthorizationCodeFlow where
11371258-- Manual ToJSON instances
11381259-- =======================================================================
11391260
1140−instance (Eq p, ToJSON p, AesonDefaultValue p) =>ToJSON (OAuth2Flow p) where
1261+instance ToJSON MediaType where
1262+ toJSON = toJSON . show
1263+ toEncoding = toEncoding . show
1264+
1265+instance ToJSONKey MediaType where
1266+ toJSONKey = JSON.toJSONKeyText (Text.pack . show)
1267+
1268+instance (Eq p, ToJSON p, AesonDefaultValue p) => ToJSON (OAuth2Flow p) where
11411269 toJSON = sopSwaggerGenericToJSON
11421270 toEncoding = sopSwaggerGenericToEncoding
11431271
@@ -1146,8 +1274,19 @@ instance ToJSON OAuth2Flows where
11461274 toEncoding = sopSwaggerGenericToEncoding
11471275
11481276instance ToJSON SecuritySchemeType where
1149− toJSON SecuritySchemeHttp
1150− = object [ "type" .= ("http" :: Text) ]
1277+ toJSON (SecuritySchemeHttp ty) = case ty of
1278+ HttpSchemeBearer mFmt ->
1279+ object $ [ "type" .= ("http" :: Text)
1280+ , "scheme" .= ("bearer" :: Text)
1281+ ] <> maybe [] (\t -> ["bearerFormat" .= t]) mFmt
1282+ HttpSchemeBasic ->
1283+ object [ "type" .= ("http" :: Text)
1284+ , "scheme" .= ("basic" :: Text)
1285+ ]
1286+ HttpSchemeCustom t ->
1287+ object [ "type" .= ("http" :: Text)
1288+ , "scheme" .= t
1289+ ]
11511290 toJSON (SecuritySchemeApiKey params)
11521291 = toJSON params
11531292 <+> object [ "type" .= ("apiKey" :: Text) ]
@@ -1160,9 +1299,9 @@ instance ToJSON SecuritySchemeType where
11601299 , "openIdConnectUrl" .= url
11611300 ]
11621301
1163−instance ToJSON Swagger where
1302+instance ToJSON OpenApi where
11641303 toJSON a = sopSwaggerGenericToJSON a &
1165− if InsOrdHashMap.null (_swaggerPaths a)
1304+ if InsOrdHashMap.null (_openApiPaths a)
11661305 then (<+> object ["paths" .= object []])
11671306 else id
11681307 toEncoding = sopSwaggerGenericToEncoding
@@ -1176,8 +1315,8 @@ instance ToJSON SecurityScheme where
11761315 toEncoding = sopSwaggerGenericToEncoding
11771316
11781317instance ToJSON Schema where
1179− toJSON = sopSwaggerGenericToJSON
1180− toEncoding = sopSwaggerGenericToEncoding
1318+ toJSON = sopSwaggerGenericToJSONWithOpts $
1319+ mkSwaggerAesonOptions "schema" & saoSubObject ?~ "items"
11811320
11821321instance ToJSON Header where
11831322 toJSON = sopSwaggerGenericToJSON
@@ -1186,17 +1325,21 @@ instance ToJSON Header where
11861325-- | As for nullary schema for 0-arity type constructors, see
11871326-- <https://github.com/GetShopTV/swagger2/issues/167>.
11881327--
1189−-- >>> encode (SwaggerItemsArray [])
1190−-- "{\"example\":[],\"items\":{},\"maxItems\":0}"
1328+-- >>> BSL.putStrLn $ encodePretty (OpenApiItemsArray [])
1329+-- {
1330+-- "example": [],
1331+-- "items": {},
1332+-- "maxItems": 0
1333+-- }
11911334--
1192−instance ToJSON SwaggerItems where
1193− toJSON (SwaggerItemsObject x) = object [ "items" .= x ]
1194− toJSON (SwaggerItemsArray []) = object
1335+instance ToJSON OpenApiItems where
1336+ toJSON (OpenApiItemsObject x) = object [ "items" .= x ]
1337+ toJSON (OpenApiItemsArray []) = object
11951338 [ "items" .= object []
11961339 , "maxItems" .= (0 :: Int)
11971340 , "example" .= Array mempty
11981341 ]
1199− toJSON (SwaggerItemsArray x) = object [ "items" .= x ]
1342+ toJSON (OpenApiItemsArray x) = object [ "items" .= x ]
12001343
12011344instance ToJSON Components where
12021345 toJSON = sopSwaggerGenericToJSON
@@ -1241,6 +1384,10 @@ instance ToJSON Encoding where
12411384 toJSON = sopSwaggerGenericToJSON
12421385 toEncoding = sopSwaggerGenericToEncoding
12431386
1387+instance ToJSON Link where
1388+ toJSON = sopSwaggerGenericToJSON
1389+ toEncoding = sopSwaggerGenericToEncoding
1390+
12441391instance ToJSON SecurityDefinitions where
12451392 toJSON (SecurityDefinitions sd) = toJSON sd
12461393
@@ -1257,20 +1404,31 @@ instance ToJSON (Referenced Response) where toJSON = referencedToJSON "#/compone
12571404instance ToJSON (Referenced RequestBody) where toJSON = referencedToJSON "#/components/requestBodies/"
12581405instance ToJSON (Referenced Example) where toJSON = referencedToJSON "#/components/examples/"
12591406instance ToJSON (Referenced Header) where toJSON = referencedToJSON "#/components/headers/"
1260−
1261−instance ToJSON ParamSchema where
1262− -- TODO: this is a bit fishy, why we need sub object only in `ToJSON`?
1263− toJSON = sopSwaggerGenericToJSONWithOpts $
1264− mkSwaggerAesonOptions "paramSchema" & saoSubObject ?~ "items"
1407+instance ToJSON (Referenced Link) where toJSON = referencedToJSON "#/components/links/"
1408+instance ToJSON (Referenced Callback) where toJSON = referencedToJSON "#/components/callbacks/"
12651409
12661410instance ToJSON AdditionalProperties where
12671411 toJSON (AdditionalPropertiesAllowed b) = toJSON b
12681412 toJSON (AdditionalPropertiesSchema s) = toJSON s
12691413
1414+instance ToJSON ExpressionOrValue where
1415+ toJSON (Expression expr) = toJSON expr
1416+ toJSON (Value val) = toJSON val
1417+
1418+instance ToJSON Callback where
1419+ toJSON (Callback ps) = toJSON ps
1420+
12701421-- =======================================================================
12711422-- Manual FromJSON instances
12721423-- =======================================================================
12731424
1425+instance FromJSON MediaType where
1426+ parseJSON = withText "MediaType" $ \str ->
1427+ maybe (fail $ "Invalid media type literal " <> Text.unpack str) pure $ parseAccept $ encodeUtf8 str
1428+
1429+instance FromJSONKey MediaType where
1430+ fromJSONKey = FromJSONKeyTextParser (parseJSON . String)
1431+
12741432instance (Eq p, FromJSON p, AesonDefaultValue p) => FromJSON (OAuth2Flow p) where
12751433 parseJSON = sopSwaggerGenericParseJSON
12761434
@@ -1281,14 +1439,19 @@ instance FromJSON SecuritySchemeType where
12811439 parseJSON js@(Object o) = do
12821440 (t :: Text) <- o .: "type"
12831441 case t of
1284− "http" -> pure SecuritySchemeHttp
1442+ "http" -> do
1443+ scheme <- o .: "scheme"
1444+ SecuritySchemeHttp <$> case scheme of
1445+ "bearer" -> HttpSchemeBearer <$> (o .:! "bearerFormat")
1446+ "basic" -> pure HttpSchemeBasic
1447+ t -> pure $ HttpSchemeCustom t
12851448 "apiKey" -> SecuritySchemeApiKey <$> parseJSON js
12861449 "oauth2" -> SecuritySchemeOAuth2 <$> (o .: "flows")
12871450 "openIdConnect" -> SecuritySchemeOpenIdConnect <$> (o .: "openIdConnectUrl")
12881451 _ -> empty
12891452 parseJSON _ = empty
12901453
1291−instance FromJSON Swagger where
1454+instance FromJSON OpenApi where
12921455 parseJSON = sopSwaggerGenericParseJSON
12931456
12941457instance FromJSON Server where
@@ -1300,27 +1463,28 @@ instance FromJSON SecurityScheme where
13001463instance FromJSON Schema where
13011464 parseJSON = fmap nullaryCleanup . sopSwaggerGenericParseJSON
13021465 where nullaryCleanup :: Schema -> Schema
1303− nullaryCleanup s@Schema{_schemaParamSchema=ps} =
1304− if _paramSchemaItems ps == Just (SwaggerItemsArray [])
1466+ nullaryCleanup s =
1467+ if _schemaItems s == Just (OpenApiItemsArray [])
13051468 then s { _schemaExample = Nothing
1306− , _schemaParamSchema = ps { _paramSchemaMaxItems = Nothing } }
1469+ , _schemaMaxItems = Nothing
1470+ }
13071471 else s
13081472
13091473instance FromJSON Header where
13101474 parseJSON = sopSwaggerGenericParseJSON
13111475
1312−instance FromJSON SwaggerItems where
1476+instance FromJSON OpenApiItems where
13131477 parseJSON js@(Object obj)
1314− | null obj = pure $ SwaggerItemsArray [] -- Nullary schema.
1315− | otherwise = SwaggerItemsObject <$> parseJSON js
1316− parseJSON js@(Array _) = SwaggerItemsArray <$> parseJSON js
1478+ | null obj = pure $ OpenApiItemsArray [] -- Nullary schema.
1479+ | otherwise = OpenApiItemsObject <$> parseJSON js
1480+ parseJSON js@(Array _) = OpenApiItemsArray <$> parseJSON js
13171481 parseJSON _ = empty
13181482
13191483instance FromJSON Components where
13201484 parseJSON = sopSwaggerGenericParseJSON
13211485
13221486instance FromJSON MimeList where
1323− parseJSON js = (MimeList . map fromString) <$> parseJSON js
1487+ parseJSON js = MimeList . map fromString <$> parseJSON js
13241488
13251489instance FromJSON Param where
13261490 parseJSON = sopSwaggerGenericParseJSON
@@ -1328,7 +1492,7 @@ instance FromJSON Param where
13281492instance FromJSON Responses where
13291493 parseJSON (Object o) = Responses
13301494 <$> o .:? "default"
1331− <*> (parseJSON (Object (HashMap.delete "default" o)))
1495+ <*> parseJSON (Object (deleteKey "default" o))
13321496 parseJSON _ = empty
13331497
13341498instance FromJSON Example where
@@ -1355,6 +1519,9 @@ instance FromJSON MediaTypeObject where
13551519instance FromJSON Encoding where
13561520 parseJSON = sopSwaggerGenericParseJSON
13571521
1522+instance FromJSON Link where
1523+ parseJSON = sopSwaggerGenericParseJSON
1524+
13581525instance FromJSON Reference where
13591526 parseJSON (Object o) = Reference <$> o .: "$ref"
13601527 parseJSON _ = empty
@@ -1378,17 +1545,24 @@ instance FromJSON (Referenced Response) where parseJSON = referencedParseJSON "#
13781545instance FromJSON (Referenced RequestBody) where parseJSON = referencedParseJSON "#/components/requestBodies/"
13791546instance FromJSON (Referenced Example) where parseJSON = referencedParseJSON "#/components/examples/"
13801547instance FromJSON (Referenced Header) where parseJSON = referencedParseJSON "#/components/headers/"
1548+instance FromJSON (Referenced Link) where parseJSON = referencedParseJSON "#/components/links/"
1549+instance FromJSON (Referenced Callback) where parseJSON = referencedParseJSON "#/components/callbacks/"
13811550
13821551instance FromJSON Xml where
13831552 parseJSON = genericParseJSON (jsonPrefix "xml")
13841553
1385−instance FromJSON ParamSchema where
1386− parseJSON = sopSwaggerGenericParseJSON
1387−
13881554instance FromJSON AdditionalProperties where
13891555 parseJSON (Bool b) = pure $ AdditionalPropertiesAllowed b
13901556 parseJSON js = AdditionalPropertiesSchema <$> parseJSON js
13911557
1558+-- | All strings are parsed as expressions
1559+instance FromJSON ExpressionOrValue where
1560+ parseJSON (String expr) = pure $ Expression expr
1561+ parseJSON v = pure $ Value v
1562+
1563+instance FromJSON Callback where
1564+ parseJSON = fmap Callback . parseJSON
1565+
13921566instance HasSwaggerAesonOptions Server where
13931567 swaggerAesonOptions _ = mkSwaggerAesonOptions "server"
13941568instance HasSwaggerAesonOptions Components where
@@ -1417,19 +1591,18 @@ instance HasSwaggerAesonOptions SecurityScheme where
14171591 swaggerAesonOptions _ = mkSwaggerAesonOptions "securityScheme" & saoSubObject ?~ "type"
14181592instance HasSwaggerAesonOptions Schema where
14191593 swaggerAesonOptions _ = mkSwaggerAesonOptions "schema" & saoSubObject ?~ "paramSchema"
1420−instance HasSwaggerAesonOptions Swagger where
1594+instance HasSwaggerAesonOptions OpenApi where
14211595 swaggerAesonOptions _ = mkSwaggerAesonOptions "swagger" & saoAdditionalPairs .~ [("openapi", "3.0.0")]
14221596instance HasSwaggerAesonOptions Example where
14231597 swaggerAesonOptions _ = mkSwaggerAesonOptions "example"
14241598instance HasSwaggerAesonOptions Encoding where
14251599 swaggerAesonOptions _ = mkSwaggerAesonOptions "encoding"
14261600
1427−instance HasSwaggerAesonOptions ParamSchema where
1428− swaggerAesonOptions _ = mkSwaggerAesonOptions "paramSchema"
1601+instance HasSwaggerAesonOptions Link where
1602+ swaggerAesonOptions _ = mkSwaggerAesonOptions "link"
14291603
14301604instance AesonDefaultValue Server
14311605instance AesonDefaultValue Components
1432−instance AesonDefaultValue ParamSchema
14331606instance AesonDefaultValue OAuth2ImplicitFlow
14341607instance AesonDefaultValue OAuth2PasswordFlow
14351608instance AesonDefaultValue OAuth2ClientCredentialsFlow
@@ -1437,7 +1610,10 @@ instance AesonDefaultValue OAuth2AuthorizationCodeFlow
14371610instance AesonDefaultValue p => AesonDefaultValue (OAuth2Flow p)
14381611instance AesonDefaultValue Responses
14391612instance AesonDefaultValue SecuritySchemeType
1440−instance AesonDefaultValue SwaggerType
1613+instance AesonDefaultValue OpenApiType
14411614instance AesonDefaultValue MimeList where defaultValue = Just mempty
14421615instance AesonDefaultValue Info
14431616instance AesonDefaultValue ParamLocation
1617+instance AesonDefaultValue Link
1618+instance AesonDefaultValue SecurityDefinitions where
1619+ defaultValue = Just mempty