{-# LANGUAGE AllowAmbiguousTypes, UndecidableInstances, LambdaCase #-}
module IHP.RouterSupport (
CanRoute (..)
, HasPath (..)
, AutoRoute (..)
, runAction
, get
, post
, startPage
, frontControllerToWAIApp
, withPrefix
, FrontController (..)
, parseRoute
, catchAll
, mountFrontController
, createAction
, updateAction
, urlTo
, parseUUID
, parseId
, parseIntegerId
, remainingText
, parseText
, webSocketApp
, webSocketAppWithCustomPath
) where

import qualified Prelude
import ClassyPrelude hiding (index, delete, take)
import qualified IHP.ModelSupport as ModelSupport
import IHP.FrameworkConfig
import IHP.ApplicationContext hiding (frameworkConfig)
import Data.UUID
import Network.HTTP.Types.Method
import GHC.Records
import IHP.Controller.RequestContext
import Network.Wai
import IHP.ControllerSupport
import Data.Attoparsec.ByteString.Char8 (string, Parser, parseOnly, take, endOfInput, choice, takeTill, takeByteString)
import qualified Data.Attoparsec.ByteString.Char8 as Attoparsec
import GHC.TypeLits
import Data.Data
import qualified Control.Monad.State.Strict as State
import qualified Data.Text as Text
import Network.HTTP.Types.URI
import qualified Data.List as List
import Unsafe.Coerce
import IHP.HaskellSupport hiding (get)
import qualified Data.Typeable as Typeable
import qualified Data.ByteString.Char8 as ByteString
import qualified Data.Char as Char
import Control.Monad.Fail
import Data.String.Conversions (ConvertibleStrings (convertString), cs)
import qualified Text.Blaze.Html5 as Html5
import qualified IHP.ErrorController as ErrorController
import qualified Control.Exception as Exception
import qualified Data.List.Split as List
import qualified Network.URI.Encode as URI
import qualified Data.Text.Encoding as Text
import Data.Dynamic
import IHP.Router.Types
import IHP.WebSocket (WSApp)
import GHC.TypeLits as T

class FrontController application where
    controllers :: (?applicationContext :: ApplicationContext, ?application :: application, ?context :: RequestContext) => [Parser (IO ResponseReceived)]

class HasPath controller where
    -- | Returns the path to a given action
    --
    -- >>> pathTo UsersAction
    -- "/Users"
    --
    -- >>> pathTo ShowUserAction { userId = "a32913dd-ef80-4f3e-9a91-7879e17b2ece" }
    -- "/ShowUser?userId=a32913dd-ef80-4f3e-9a91-7879e17b2ece"
    pathTo :: controller -> Text

-- | Returns the url to a given action.
--
-- Uses the baseUrl configured in @Config/Config.hs@. When no @baseUrl@
-- is configured in development mode, it will automatically detect the
-- correct @baseUrl@ value.
--
-- >>> urlTo UsersAction
-- "http://localhost:8000/Users"
--
-- >>> urlTo ShowUserAction { userId = "a32913dd-ef80-4f3e-9a91-7879e17b2ece" }
-- "http://localhost:8000/ShowUser?userId=a32913dd-ef80-4f3e-9a91-7879e17b2ece"
urlTo :: (?context :: context, ConfigProvider context, HasPath action) => action -> Text
urlTo :: action -> Text
urlTo action
action = ((FrameworkConfig -> Text) -> Text
forall context a.
(?context::context, ConfigProvider context) =>
(FrameworkConfig -> a) -> a
fromConfig FrameworkConfig -> Text
baseUrl) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> action -> Text
forall controller. HasPath controller => controller -> Text
pathTo action
action
{-# INLINE urlTo #-}

class HasPath controller => CanRoute controller where
    parseRoute' :: (?context :: RequestContext) => Parser controller


-- | Each of these is tried when trying to parse an argument to a controller constructor (i.e. in IHP, an action).
-- The type @d@ is an the type of the argument, and all we know about this type that its conforms to @Data@.
-- We cannot cast @d@ to some arbitrary type, since adding additional constraints to @d@ (such as Read)
-- will break the @fromConstrM@ function which actually constructs the action.
--
-- The approach taken here is to make use of the type equality operator @:~:@
-- to check and see if @d@ happens to be a certain type. If it is,
-- by matching on Just Refl, we are able to use @d@ as the type we matched it to.
--
-- Please consult your doctor before engaging in Haskell type programming.
parseFuncs :: forall d idType. (Data d, Data idType) => (ByteString -> Maybe idType) -> [Maybe ByteString -> Either TypedAutoRouteError d]
parseFuncs :: (ByteString -> Maybe idType)
-> [Maybe ByteString -> Either TypedAutoRouteError d]
parseFuncs ByteString -> Maybe idType
parseIdType = [
            -- Try and parse @Int@ or @Maybe Int@
            \case
                Just ByteString
queryValue -> case Maybe (d :~: Int)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Int) of
                    Just d :~: Int
Refl -> String -> Maybe d
forall c a.
(Element c ~ Char, MonoFoldable c, Read a) =>
c -> Maybe a
readMay (ByteString -> String
forall a b. ConvertibleStrings a b => a -> b
cs ByteString
queryValue :: String)
                        Maybe d
-> (Maybe d -> Either TypedAutoRouteError d)
-> Either TypedAutoRouteError d
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> \case
                            Just d
int -> d -> Either TypedAutoRouteError d
forall a b. b -> Either a b
Right d
int
                            Maybe d
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left BadType :: ByteString -> Maybe ByteString -> ByteString -> TypedAutoRouteError
BadType { $sel:field:BadType :: ByteString
field = ByteString
"", $sel:value:BadType :: Maybe ByteString
value = ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
queryValue, $sel:expectedType:BadType :: ByteString
expectedType = ByteString
"Int" }
                    Maybe (d :~: Int)
Nothing -> case Maybe (d :~: Maybe Int)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Maybe Int) of
                        Just d :~: Maybe Int
Refl -> Maybe Int -> Either TypedAutoRouteError (Maybe Int)
forall a b. b -> Either a b
Right (Maybe Int -> Either TypedAutoRouteError (Maybe Int))
-> Maybe Int -> Either TypedAutoRouteError (Maybe Int)
forall a b. (a -> b) -> a -> b
$ String -> Maybe Int
forall c a.
(Element c ~ Char, MonoFoldable c, Read a) =>
c -> Maybe a
readMay (ByteString -> String
forall a b. ConvertibleStrings a b => a -> b
cs ByteString
queryValue :: String)
                        Maybe (d :~: Maybe Int)
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched
                Maybe ByteString
Nothing -> case Maybe (d :~: Maybe Int)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Maybe Int) of
                    Just d :~: Maybe Int
Refl -> Maybe Int -> Either TypedAutoRouteError (Maybe Int)
forall a b. b -> Either a b
Right Maybe Int
forall a. Maybe a
Nothing
                    Maybe (d :~: Maybe Int)
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched,

            \case
                Just ByteString
queryValue -> case Maybe (d :~: Integer)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Integer) of
                    Just d :~: Integer
Refl -> String -> Maybe d
forall c a.
(Element c ~ Char, MonoFoldable c, Read a) =>
c -> Maybe a
readMay (ByteString -> String
forall a b. ConvertibleStrings a b => a -> b
cs ByteString
queryValue :: String)
                        Maybe d
-> (Maybe d -> Either TypedAutoRouteError d)
-> Either TypedAutoRouteError d
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> \case
                            Just d
int -> d -> Either TypedAutoRouteError d
forall a b. b -> Either a b
Right d
int
                            Maybe d
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left BadType :: ByteString -> Maybe ByteString -> ByteString -> TypedAutoRouteError
BadType { $sel:field:BadType :: ByteString
field = ByteString
"", $sel:value:BadType :: Maybe ByteString
value = ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
queryValue, $sel:expectedType:BadType :: ByteString
expectedType = ByteString
"Integer" }
                    Maybe (d :~: Integer)
Nothing -> case Maybe (d :~: Maybe Integer)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Maybe Integer) of
                        Just d :~: Maybe Integer
Refl -> Maybe Integer -> Either TypedAutoRouteError (Maybe Integer)
forall a b. b -> Either a b
Right (Maybe Integer -> Either TypedAutoRouteError (Maybe Integer))
-> Maybe Integer -> Either TypedAutoRouteError (Maybe Integer)
forall a b. (a -> b) -> a -> b
$ String -> Maybe Integer
forall c a.
(Element c ~ Char, MonoFoldable c, Read a) =>
c -> Maybe a
readMay (ByteString -> String
forall a b. ConvertibleStrings a b => a -> b
cs ByteString
queryValue :: String)
                        Maybe (d :~: Maybe Integer)
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched
                Maybe ByteString
Nothing -> case Maybe (d :~: Maybe Integer)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Maybe Integer) of
                    Just d :~: Maybe Integer
Refl -> Maybe Integer -> Either TypedAutoRouteError (Maybe Integer)
forall a b. b -> Either a b
Right Maybe Integer
forall a. Maybe a
Nothing
                    Maybe (d :~: Maybe Integer)
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched,

            -- Try and parse @Text@ or @Maybe Text@
            \case
                Just ByteString
queryValue -> case Maybe (d :~: Text)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Text) of
                    Just d :~: Text
Refl -> d -> Either TypedAutoRouteError d
forall a b. b -> Either a b
Right (d -> Either TypedAutoRouteError d)
-> d -> Either TypedAutoRouteError d
forall a b. (a -> b) -> a -> b
$ ByteString -> d
forall a b. ConvertibleStrings a b => a -> b
cs ByteString
queryValue
                    Maybe (d :~: Text)
Nothing -> case Maybe (d :~: Maybe Text)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Maybe Text) of
                        Just d :~: Maybe Text
Refl -> Maybe Text -> Either TypedAutoRouteError (Maybe Text)
forall a b. b -> Either a b
Right (Maybe Text -> Either TypedAutoRouteError (Maybe Text))
-> Maybe Text -> Either TypedAutoRouteError (Maybe Text)
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ ByteString -> Text
forall a b. ConvertibleStrings a b => a -> b
cs ByteString
queryValue
                        Maybe (d :~: Maybe Text)
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched
                Maybe ByteString
Nothing -> case Maybe (d :~: Maybe Text)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Maybe Text) of
                    Just d :~: Maybe Text
Refl -> Maybe Text -> Either TypedAutoRouteError (Maybe Text)
forall a b. b -> Either a b
Right Maybe Text
forall a. Maybe a
Nothing
                    Maybe (d :~: Maybe Text)
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched,
            \case
                Just ByteString
queryValue -> case ByteString -> Maybe idType
parseIdType ByteString
queryValue of
                    Just idType
idValue -> case Maybe (d :~: idType)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: idType) of
                        Just d :~: idType
Refl -> idType -> Either TypedAutoRouteError idType
forall a b. b -> Either a b
Right idType
idValue
                        Maybe (d :~: idType)
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched
                    Maybe idType
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched
                Maybe ByteString
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched,

            -- Try and parse @[Text]@. If value is not present then default to empty list.
            \Maybe ByteString
queryValue -> case Maybe (d :~: [Text])
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: [Text]) of
                Just d :~: [Text]
Refl -> case Maybe ByteString
queryValue of
                    Just ByteString
queryValue -> [Text] -> Either TypedAutoRouteError [Text]
forall a b. b -> Either a b
Right ([Text] -> Either TypedAutoRouteError [Text])
-> [Text] -> Either TypedAutoRouteError [Text]
forall a b. (a -> b) -> a -> b
$ Text -> Text -> [Text]
Text.splitOn Text
"," (ByteString -> Text
forall a b. ConvertibleStrings a b => a -> b
cs ByteString
queryValue)
                    Maybe ByteString
Nothing -> [Text] -> Either TypedAutoRouteError [Text]
forall a b. b -> Either a b
Right []
                Maybe (d :~: [Text])
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched,

            -- Try and parse @[Int]@. If value is not present then default to empty list.
            \Maybe ByteString
queryValue -> case Maybe (d :~: [Int])
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: [Int]) of
                Just d :~: [Int]
Refl -> case Maybe ByteString
queryValue of
                    Just ByteString
queryValue -> Text -> Text -> [Text]
Text.splitOn Text
"," (ByteString -> Text
forall a b. ConvertibleStrings a b => a -> b
cs ByteString
queryValue)
                        [Text] -> ([Text] -> [Maybe Int]) -> [Maybe Int]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> (Text -> Maybe Int) -> [Text] -> [Maybe Int]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map Text -> Maybe Int
forall c a.
(Element c ~ Char, MonoFoldable c, Read a) =>
c -> Maybe a
readMay
                        [Maybe Int] -> ([Maybe Int] -> [Int]) -> [Int]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> [Maybe Int] -> [Int]
forall (f :: * -> *) t.
(IsSequence (f (Maybe t)), Functor f,
 Element (f (Maybe t)) ~ Maybe t) =>
f (Maybe t) -> f t
catMaybes
                        [Int]
-> ([Int] -> Either TypedAutoRouteError [Int])
-> Either TypedAutoRouteError [Int]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> [Int] -> Either TypedAutoRouteError [Int]
forall a b. b -> Either a b
Right
                    Maybe ByteString
Nothing -> [Int] -> Either TypedAutoRouteError [Int]
forall a b. b -> Either a b
Right []
                Maybe (d :~: [Int])
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched,

            \Maybe ByteString
queryValue -> case Maybe (d :~: [Integer])
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: [Integer]) of
                Just d :~: [Integer]
Refl -> case Maybe ByteString
queryValue of
                    Just ByteString
queryValue -> Text -> Text -> [Text]
Text.splitOn Text
"," (ByteString -> Text
forall a b. ConvertibleStrings a b => a -> b
cs ByteString
queryValue)
                        [Text] -> ([Text] -> [Maybe Integer]) -> [Maybe Integer]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> (Text -> Maybe Integer) -> [Text] -> [Maybe Integer]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map Text -> Maybe Integer
forall c a.
(Element c ~ Char, MonoFoldable c, Read a) =>
c -> Maybe a
readMay
                        [Maybe Integer] -> ([Maybe Integer] -> [Integer]) -> [Integer]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> [Maybe Integer] -> [Integer]
forall (f :: * -> *) t.
(IsSequence (f (Maybe t)), Functor f,
 Element (f (Maybe t)) ~ Maybe t) =>
f (Maybe t) -> f t
catMaybes
                        [Integer]
-> ([Integer] -> Either TypedAutoRouteError [Integer])
-> Either TypedAutoRouteError [Integer]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> [Integer] -> Either TypedAutoRouteError [Integer]
forall a b. b -> Either a b
Right
                    Maybe ByteString
Nothing -> [Integer] -> Either TypedAutoRouteError [Integer]
forall a b. b -> Either a b
Right []
                Maybe (d :~: [Integer])
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched,

            -- Try and parse a raw UUID
            \Maybe ByteString
queryValue -> case Maybe (d :~: UUID)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: UUID) of
                Just d :~: UUID
Refl -> case Maybe ByteString
queryValue of
                    Just ByteString
queryValue -> ByteString
queryValue
                        ByteString -> (ByteString -> Maybe UUID) -> Maybe UUID
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> ByteString -> Maybe UUID
fromASCIIBytes
                        Maybe UUID
-> (Maybe UUID -> Either TypedAutoRouteError UUID)
-> Either TypedAutoRouteError UUID
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> \case
                            Just UUID
uuid -> UUID
uuid UUID
-> (UUID -> Either TypedAutoRouteError UUID)
-> Either TypedAutoRouteError UUID
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> UUID -> Either TypedAutoRouteError UUID
forall a b. b -> Either a b
Right
                            Maybe UUID
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError UUID
forall a b. a -> Either a b
Left BadType :: ByteString -> Maybe ByteString -> ByteString -> TypedAutoRouteError
BadType { $sel:field:BadType :: ByteString
field = ByteString
"", $sel:value:BadType :: Maybe ByteString
value = ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
queryValue, $sel:expectedType:BadType :: ByteString
expectedType = ByteString
"UUID" }
                    Maybe ByteString
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched
                Maybe (d :~: UUID)
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched,

            -- This has to be last parser in the list
            --
            -- Try and parse a UUID wrapped with a Id. In IHP types these are wrapped in a newtype @Id@ such as @Id User@.
            -- Since @Id@ is a newtype wrapping a UUID, it has the same data representation in GHC.
            -- Therefore, we're able to safely cast it to its @Id@ type with @unsafeCoerce@.
            --
            -- We cannot use 'eqT' here for checking the types, as it's wrapped inside the @Id@ type. We expect
            -- that if it looks like a UUID, we can just treat it like an @Id@ type. For that to not overshadow other
            -- parsers, we need to have this last.
            \Maybe ByteString
queryValue -> case Maybe ByteString
queryValue of
                Just ByteString
queryValue -> ByteString
queryValue
                    ByteString -> (ByteString -> Maybe UUID) -> Maybe UUID
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> ByteString -> Maybe UUID
fromASCIIBytes
                    Maybe UUID
-> (Maybe UUID -> Either TypedAutoRouteError d)
-> Either TypedAutoRouteError d
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> \case
                        Just UUID
uuid -> UUID
uuid UUID -> (UUID -> d) -> d
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> UUID -> d
forall a b. a -> b
unsafeCoerce d
-> (d -> Either TypedAutoRouteError d)
-> Either TypedAutoRouteError d
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> d -> Either TypedAutoRouteError d
forall a b. b -> Either a b
Right
                        Maybe UUID
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left BadType :: ByteString -> Maybe ByteString -> ByteString -> TypedAutoRouteError
BadType { $sel:field:BadType :: ByteString
field = ByteString
"", $sel:value:BadType :: Maybe ByteString
value = ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
queryValue, $sel:expectedType:BadType :: ByteString
expectedType = ByteString
"UUID" }
                Maybe ByteString
Nothing -> TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
NotMatched
            ]

-- | As we fold over a constructor, we want the values parsed from the query string
-- to be in the same order as they are in the constructor.
-- This function uses the field labels from the constructor to sort the values from
-- the query string. As a consequence, constructors with basic record syntax will not work with auto types.
--
-- @data MyController = MyAction Text Int@
--
-- does not work. Instead use,
--
-- @data MyController = MyAction { textArg :: Text, intArg :: Int }@
querySortedByFields :: Query -> Constr -> Query
querySortedByFields :: Query -> Constr -> Query
querySortedByFields Query
query Constr
constructor = Constr -> [String]
constrFields Constr
constructor
        [String] -> ([String] -> [ByteString]) -> [ByteString]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> (String -> ByteString) -> [String] -> [ByteString]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map String -> ByteString
forall a b. ConvertibleStrings a b => a -> b
cs
        [ByteString] -> ([ByteString] -> Query) -> Query
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> (ByteString -> (ByteString, Maybe ByteString))
-> [ByteString] -> Query
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map (\ByteString
field -> (ByteString
field, Maybe (Maybe ByteString) -> Maybe ByteString
forall (m :: * -> *) a. Monad m => m (m a) -> m a
join (Maybe (Maybe ByteString) -> Maybe ByteString)
-> Maybe (Maybe ByteString) -> Maybe ByteString
forall a b. (a -> b) -> a -> b
$ ByteString -> Query -> Maybe (Maybe ByteString)
forall a b. Eq a => a -> [(a, b)] -> Maybe b
List.lookup ByteString
field Query
query))

-- | Given a constructor and a parsed query string, attempt to construct a value of the constructor's type.
-- For example, given the controller
--
-- @data MyController = MyAction { textArg :: Text, intArg :: Int }@
--
-- this function will receive a representation of the @MyAction@ constructor as well as some query string
-- @[("textArg", "some text"), ("intArg", "123")]@.
--
-- By iterating through the query and attempting to match the type of each constructor argument
-- with some transformation of the query string, we attempt to call @MyAction@.
applyConstr :: (Data controller, Data idType) => (ByteString -> Maybe idType) -> Constr -> Query -> Either TypedAutoRouteError controller
applyConstr :: (ByteString -> Maybe idType)
-> Constr -> Query -> Either TypedAutoRouteError controller
applyConstr ByteString -> Maybe idType
parseIdType Constr
constructor Query
query = let

    -- | Given some query item (key, optional value), try to parse into the current expected type
    -- by iterating through the available parse functions.
    attemptToParseArg :: forall d. (Data d) => (ByteString, Maybe ByteString) -> [Maybe ByteString -> Either TypedAutoRouteError d] -> State.StateT Query (Either TypedAutoRouteError) d
    attemptToParseArg :: (ByteString, Maybe ByteString)
-> [Maybe ByteString -> Either TypedAutoRouteError d]
-> StateT Query (Either TypedAutoRouteError) d
attemptToParseArg queryParam :: (ByteString, Maybe ByteString)
queryParam@(ByteString
queryName, Maybe ByteString
queryValue) [] = Either TypedAutoRouteError d
-> StateT Query (Either TypedAutoRouteError) d
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
State.lift (TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left NoConstructorMatched :: ByteString -> Maybe ByteString -> ByteString -> TypedAutoRouteError
NoConstructorMatched
                { $sel:field:BadType :: ByteString
field = ByteString
queryName
                , $sel:value:BadType :: Maybe ByteString
value = Maybe ByteString
queryValue
                , $sel:expectedType:BadType :: ByteString
expectedType = (d -> DataType
forall a. Data a => a -> DataType
dataTypeOf (d
forall a. HasCallStack => a
undefined :: d)) DataType -> (DataType -> String) -> String
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> DataType -> String
dataTypeName String -> (String -> ByteString) -> ByteString
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> String -> ByteString
forall a b. ConvertibleStrings a b => a -> b
cs
                })
    attemptToParseArg queryParam :: (ByteString, Maybe ByteString)
queryParam@(ByteString
k, Maybe ByteString
v) (Maybe ByteString -> Either TypedAutoRouteError d
parseFunc:[Maybe ByteString -> Either TypedAutoRouteError d]
restFuncs) = case Maybe ByteString -> Either TypedAutoRouteError d
parseFunc Maybe ByteString
v of
            Right d
result -> d -> StateT Query (Either TypedAutoRouteError) d
forall (f :: * -> *) a. Applicative f => a -> f a
pure d
result
            -- BadType will be returned if, for example, a text is passed to a query parameter typed as int.
            Left badType :: TypedAutoRouteError
badType@BadType{} -> Either TypedAutoRouteError d
-> StateT Query (Either TypedAutoRouteError) d
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
State.lift (TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
badType { $sel:field:BadType :: ByteString
field = ByteString
k })
            -- otherwise, safe to assume the match just failed, so recurse on the rest of the functions and try to find one that matches.
            Left TypedAutoRouteError
_ -> (ByteString, Maybe ByteString)
-> [Maybe ByteString -> Either TypedAutoRouteError d]
-> StateT Query (Either TypedAutoRouteError) d
forall d.
Data d =>
(ByteString, Maybe ByteString)
-> [Maybe ByteString -> Either TypedAutoRouteError d]
-> StateT Query (Either TypedAutoRouteError) d
attemptToParseArg (ByteString, Maybe ByteString)
queryParam [Maybe ByteString -> Either TypedAutoRouteError d]
restFuncs

    -- | Attempt to parse the current expected type, and return its value.
    -- For the example @MyController@ this is called twice by @fromConstrM@.
    -- Once, it is called for @textArg@ where @d :: Text@. Then it is called
    -- for @intArg@ with @d ::: Int@. With both of these values parsed from the query string,
    -- the controller action is able to be created.
    nextField :: forall d. (Data d) => State.StateT Query (Either TypedAutoRouteError) d
    nextField :: StateT Query (Either TypedAutoRouteError) d
nextField = do
            Query
queryParams <- StateT Query (Either TypedAutoRouteError) Query
forall s (m :: * -> *). MonadState s m => m s
State.get
            case Query
queryParams of
                [] -> Either TypedAutoRouteError d
-> StateT Query (Either TypedAutoRouteError) d
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
State.lift (TypedAutoRouteError -> Either TypedAutoRouteError d
forall a b. a -> Either a b
Left TypedAutoRouteError
TooFewArguments)
                (p :: (ByteString, Maybe ByteString)
p@(ByteString
key, Maybe ByteString
value):Query
rest) -> do
                    Query -> StateT Query (Either TypedAutoRouteError) ()
forall s (m :: * -> *). MonadState s m => s -> m ()
State.put Query
rest
                    (ByteString, Maybe ByteString)
-> [Maybe ByteString -> Either TypedAutoRouteError d]
-> StateT Query (Either TypedAutoRouteError) d
forall d.
Data d =>
(ByteString, Maybe ByteString)
-> [Maybe ByteString -> Either TypedAutoRouteError d]
-> StateT Query (Either TypedAutoRouteError) d
attemptToParseArg (ByteString, Maybe ByteString)
p ((ByteString -> Maybe idType)
-> [Maybe ByteString -> Either TypedAutoRouteError d]
forall d idType.
(Data d, Data idType) =>
(ByteString -> Maybe idType)
-> [Maybe ByteString -> Either TypedAutoRouteError d]
parseFuncs ByteString -> Maybe idType
parseIdType)


   in case StateT Query (Either TypedAutoRouteError) controller
-> Query -> Either TypedAutoRouteError (controller, Query)
forall s (m :: * -> *) a. StateT s m a -> s -> m (a, s)
State.runStateT ((forall d. Data d => StateT Query (Either TypedAutoRouteError) d)
-> Constr -> StateT Query (Either TypedAutoRouteError) controller
forall (m :: * -> *) a.
(Monad m, Data a) =>
(forall d. Data d => m d) -> Constr -> m a
fromConstrM forall d. Data d => StateT Query (Either TypedAutoRouteError) d
nextField Constr
constructor) (Query -> Constr -> Query
querySortedByFields Query
query Constr
constructor) of
        Right (controller
x, []) -> controller -> Either TypedAutoRouteError controller
forall (f :: * -> *) a. Applicative f => a -> f a
pure controller
x
        Right ((controller, Query)
_) -> TypedAutoRouteError -> Either TypedAutoRouteError controller
forall a b. a -> Either a b
Left TypedAutoRouteError
TooFewArguments
        Left TypedAutoRouteError
e -> TypedAutoRouteError -> Either TypedAutoRouteError controller
forall a b. a -> Either a b
Left TypedAutoRouteError
e  -- runtime type error


class Data controller => AutoRoute controller where
    autoRouteWithIdType :: (?context :: RequestContext, Data idType) => (ByteString -> Maybe idType) -> Parser controller
    autoRouteWithIdType ByteString -> Maybe idType
parseIdFunc =
        let
            allConstructors :: [Constr]
            allConstructors :: [Constr]
allConstructors = DataType -> [Constr]
dataTypeConstrs (controller -> DataType
forall a. Data a => a -> DataType
dataTypeOf (controller
forall a. HasCallStack => a
Prelude.undefined :: controller))

            query :: Query
            query :: Query
query = Request -> Query
queryString (RequestContext -> Request
forall k (x :: k) r a. HasField x r a => r -> a
getField @"request" ?context::RequestContext
RequestContext
?context)

            paramValues :: [ByteString]
            paramValues :: [ByteString]
paramValues = [Maybe ByteString] -> [ByteString]
forall (f :: * -> *) t.
(IsSequence (f (Maybe t)), Functor f,
 Element (f (Maybe t)) ~ Maybe t) =>
f (Maybe t) -> f t
catMaybes ([Maybe ByteString] -> [ByteString])
-> [Maybe ByteString] -> [ByteString]
forall a b. (a -> b) -> a -> b
$ ((ByteString, Maybe ByteString) -> Maybe ByteString)
-> Query -> [Maybe ByteString]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map (ByteString, Maybe ByteString) -> Maybe ByteString
forall a b. (a, b) -> b
snd Query
query

            parseAction :: Constr -> Parser controller
            parseAction :: Constr -> Parser controller
parseAction Constr
constr = let
                    prefix :: ByteString
                    prefix :: ByteString
prefix = String -> ByteString
ByteString.pack (Typeable controller => String
forall controller. Typeable controller => String
actionPrefix @controller)

                    actionName :: ByteString
actionName = String -> ByteString
ByteString.pack (Constr -> String
showConstr Constr
constr)

                    actionPath :: ByteString
                    actionPath :: ByteString
actionPath = ByteString -> ByteString
forall seq.
(IsSequence seq, IsString seq, Eq (Element seq)) =>
seq -> seq
stripActionSuffix ByteString
actionName

                    allowedMethods :: [StdMethod]
allowedMethods = ByteString -> [StdMethod]
forall controller.
AutoRoute controller =>
ByteString -> [StdMethod]
allowedMethodsForAction @controller ByteString
actionName

                    checkRequestMethod :: controller -> Parser controller
checkRequestMethod controller
action = do
                            StdMethod
method <- Parser StdMethod
(?context::RequestContext) => Parser StdMethod
getMethod
                            Bool -> Parser ByteString () -> Parser ByteString ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([StdMethod]
allowedMethods [StdMethod] -> ([StdMethod] -> Bool) -> Bool
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> Element [StdMethod] -> [StdMethod] -> Bool
forall container.
(MonoFoldable container, Eq (Element container)) =>
Element container -> container -> Bool
includes Element [StdMethod]
StdMethod
method) (UnexpectedMethodException -> Parser ByteString ()
forall a e. Exception e => e -> a
Exception.throw UnexpectedMethodException :: [StdMethod] -> StdMethod -> UnexpectedMethodException
UnexpectedMethodException { [StdMethod]
$sel:allowedMethods:UnexpectedMethodException :: [StdMethod]
allowedMethods :: [StdMethod]
allowedMethods, StdMethod
$sel:method:UnexpectedMethodException :: StdMethod
method :: StdMethod
method })
                            controller -> Parser controller
forall (f :: * -> *) a. Applicative f => a -> f a
pure controller
action

                    action :: Parser controller
action = case (ByteString -> Maybe idType)
-> Constr -> Query -> Either TypedAutoRouteError controller
forall controller idType.
(Data controller, Data idType) =>
(ByteString -> Maybe idType)
-> Constr -> Query -> Either TypedAutoRouteError controller
applyConstr ByteString -> Maybe idType
parseIdFunc Constr
constr Query
query of
                        Right controller
parsedAction -> controller -> Parser controller
forall (f :: * -> *) a. Applicative f => a -> f a
pure controller
parsedAction
                        Left TypedAutoRouteError
e -> TypedAutoRouteError -> Parser controller
forall a e. Exception e => e -> a
Exception.throw TypedAutoRouteError
e

                in do
                    controller
parsedAction <- ByteString -> Parser ByteString
string ByteString
prefix Parser ByteString -> Parser controller -> Parser controller
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> (ByteString -> Parser ByteString
string ByteString
actionPath Parser ByteString -> Parser ByteString () -> Parser ByteString
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Parser ByteString ()
forall t. Chunk t => Parser t ()
endOfInput) Parser ByteString -> Parser controller -> Parser controller
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> Parser controller
action
                    controller -> Parser controller
checkRequestMethod controller
parsedAction

        in [Parser controller] -> Parser controller
forall (f :: * -> *) a. Alternative f => [f a] -> f a
choice ((Constr -> Parser controller) -> [Constr] -> [Parser controller]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map Constr -> Parser controller
parseAction [Constr]
allConstructors)

    autoRoute :: (?context :: RequestContext) => Parser controller
    autoRoute = (ByteString -> Maybe Integer) -> Parser controller
forall controller idType.
(AutoRoute controller, ?context::RequestContext, Data idType) =>
(ByteString -> Maybe idType) -> Parser controller
autoRouteWithIdType (\ByteString
_ -> Maybe Integer
forall a. Maybe a
Nothing :: Maybe Integer)

    -- | Specifies the allowed HTTP methods for a given action
    --
    -- The default implementation does a smart guess based on the
    -- usual naming conventions for controllers.
    --
    -- __Example (for default implementation):__
    --
    -- >>> allowedMethodsForAction @ProjectsController "DeleteProjectAction"
    -- [DELETE]
    --
    -- >>> allowedMethodsForAction @ProjectsController "UpdateProjectAction"
    -- [POST, PATCH]
    --
    -- >>> allowedMethodsForAction @ProjectsController "CreateProjectAction"
    -- [POST]
    --
    -- >>> allowedMethodsForAction @ProjectsController "ShowProjectAction"
    -- [GET, HEAD]
    --
    -- >>> allowedMethodsForAction @ProjectsController "HelloAction"
    -- [GET, POST, HEAD]
    --
    allowedMethodsForAction :: ByteString -> [StdMethod]
    allowedMethodsForAction ByteString
actionName =
            case ByteString
actionName of
                ByteString
a | ByteString
"Delete" ByteString -> ByteString -> Bool
`ByteString.isPrefixOf` ByteString
a -> [StdMethod
DELETE]
                ByteString
a | ByteString
"Update" ByteString -> ByteString -> Bool
`ByteString.isPrefixOf` ByteString
a -> [StdMethod
POST, StdMethod
PATCH]
                ByteString
a | ByteString
"Create" ByteString -> ByteString -> Bool
`ByteString.isPrefixOf` ByteString
a -> [StdMethod
POST]
                ByteString
a | ByteString
"Show"   ByteString -> ByteString -> Bool
`ByteString.isPrefixOf` ByteString
a -> [StdMethod
GET, StdMethod
HEAD]
                ByteString
_ -> [StdMethod
GET, StdMethod
POST, StdMethod
HEAD]
    {-# INLINE allowedMethodsForAction #-}

-- | Returns the url prefix for a controller. The prefix is based on the
-- module where the controller is defined.
--
-- All controllers defined in the `Web/` directory don't have a prefix at all.
--
-- E.g. controllers in the `Admin/` directory are prefixed with @/admin/@.
actionPrefix :: forall controller. Typeable controller => String
actionPrefix :: String
actionPrefix =
        case String
moduleName of
            (Char
'W':Char
'e':Char
'b':Char
'.':String
_) -> String
"/"
            (Char
'I':Char
'H':Char
'P':Char
'.':String
_) -> String
"/"
            (String
"") -> String
"/"
            String
moduleName -> String
"/" String -> String -> String
forall a. Semigroup a => a -> a -> a
<> let (String
prefix:[String]
_) = (Char -> Bool) -> String -> [String]
forall a. (a -> Bool) -> [a] -> [[a]]
List.splitWhen (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'.') String
moduleName in (Char -> Char) -> String -> String
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map Char -> Char
Char.toLower String
prefix String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
"/"
    where
        moduleName :: String
        moduleName :: String
moduleName = controller -> TypeRep
forall a. Typeable a => a -> TypeRep
Typeable.typeOf (String -> controller
forall a. HasCallStack => String -> a
error String
"unreachable" :: controller)
                TypeRep -> (TypeRep -> TyCon) -> TyCon
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> TypeRep -> TyCon
Typeable.typeRepTyCon
                TyCon -> (TyCon -> String) -> String
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> TyCon -> String
Typeable.tyConModule
{-# INLINE actionPrefix #-}

-- | Strips the "Action" at the end of action names
--
-- >>> stripActionSuffix "ShowUserAction"
-- "ShowUser"
--
-- >>> stripActionSuffix "UsersAction"
-- "UsersAction"
--
-- >>> stripActionSuffix "User"
-- "User"
stripActionSuffix :: seq -> seq
stripActionSuffix seq
actionName = seq -> Maybe seq -> seq
forall a. a -> Maybe a -> a
fromMaybe seq
actionName (seq -> seq -> Maybe seq
forall seq.
(IsSequence seq, Eq (Element seq)) =>
seq -> seq -> Maybe seq
stripSuffix seq
"Action" seq
actionName)
{-# INLINE stripActionSuffix #-}

-- | Returns the create action for a given controller.
-- Example: `createAction @UsersController == Just CreateUserAction`
createAction :: forall controller. AutoRoute controller => Maybe controller
createAction :: Maybe controller
createAction = (Constr -> controller) -> Maybe Constr -> Maybe controller
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Constr -> controller
forall a. Data a => Constr -> a
fromConstr Maybe Constr
createConstructor
    where
        createConstructor :: Maybe Constr
        createConstructor :: Maybe Constr
createConstructor = (Element [Constr] -> Bool) -> [Constr] -> Maybe (Element [Constr])
forall seq.
SemiSequence seq =>
(Element seq -> Bool) -> seq -> Maybe (Element seq)
find Constr -> Bool
Element [Constr] -> Bool
isCreateConstructor [Constr]
allConstructors

        allConstructors :: [Constr]
        allConstructors :: [Constr]
allConstructors = DataType -> [Constr]
dataTypeConstrs (controller -> DataType
forall a. Data a => a -> DataType
dataTypeOf (controller
forall a. HasCallStack => a
Prelude.undefined :: controller))

        isCreateConstructor :: Constr -> Bool
        isCreateConstructor :: Constr -> Bool
isCreateConstructor Constr
constructor = String
"Create" String -> String -> Bool
forall seq.
(IsSequence seq, Eq (Element seq)) =>
seq -> seq -> Bool
`isPrefixOf` Constr -> String
showConstr Constr
constructor Bool -> Bool -> Bool
&& [String] -> Bool
forall mono. MonoFoldable mono => mono -> Bool
ClassyPrelude.null (Constr -> [String]
constrFields Constr
constructor)
{-# INLINE createAction #-}

-- | Returns the update action when given a controller and id.
-- Example: `updateAction @UsersController == Just (\id -> UpdateUserAction id)`
updateAction :: forall controller id. AutoRoute controller => Maybe (id -> controller)
updateAction :: Maybe (id -> controller)
updateAction =
        case Maybe Constr
updateConstructor of
            Just Constr
constructor -> (id -> controller) -> Maybe (id -> controller)
forall a. a -> Maybe a
Just ((id -> controller) -> Maybe (id -> controller))
-> (id -> controller) -> Maybe (id -> controller)
forall a b. (a -> b) -> a -> b
$ \id
id -> Constr -> id -> controller
buildInstance Constr
constructor id
id
            Maybe Constr
Nothing -> Maybe (id -> controller)
forall a. Maybe a
Nothing
    where
        updateConstructor :: Maybe Constr
        updateConstructor :: Maybe Constr
updateConstructor = (Element [Constr] -> Bool) -> [Constr] -> Maybe (Element [Constr])
forall seq.
SemiSequence seq =>
(Element seq -> Bool) -> seq -> Maybe (Element seq)
find Constr -> Bool
Element [Constr] -> Bool
isUpdateConstructor [Constr]
allConstructors

        buildInstance :: Constr -> id -> controller
        buildInstance :: Constr -> id -> controller
buildInstance Constr
constructor id
id = State Integer controller -> Integer -> controller
forall s a. State s a -> s -> a
State.evalState (((forall d. Data d => StateT Integer Identity d)
-> Constr -> State Integer controller
forall (m :: * -> *) a.
(Monad m, Data a) =>
(forall d. Data d => m d) -> Constr -> m a
fromConstrM (do
                Integer
i <- StateT Integer Identity Integer
forall s (m :: * -> *). MonadState s m => m s
State.get

                (Integer -> Integer) -> StateT Integer Identity ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
State.modify (Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+Integer
1)
                d -> StateT Integer Identity d
forall (f :: * -> *) a. Applicative f => a -> f a
pure (id -> d
forall a b. a -> b
unsafeCoerce id
id)
            )) Constr
constructor) Integer
0

        allConstructors :: [Constr]
        allConstructors :: [Constr]
allConstructors = DataType -> [Constr]
dataTypeConstrs (controller -> DataType
forall a. Data a => a -> DataType
dataTypeOf (controller
forall a. HasCallStack => a
Prelude.undefined :: controller))

        isUpdateConstructor :: Constr -> Bool
        isUpdateConstructor :: Constr -> Bool
isUpdateConstructor Constr
constructor = String
"Update" String -> String -> Bool
forall seq.
(IsSequence seq, Eq (Element seq)) =>
seq -> seq -> Bool
`isPrefixOf` (Constr -> String
showConstr Constr
constructor) Bool -> Bool -> Bool
&& ([String] -> Int
forall mono. MonoFoldable mono => mono -> Int
length (Constr -> [String]
constrFields Constr
constructor) Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1)
{-# INLINE updateAction #-}

instance {-# OVERLAPPABLE #-} (AutoRoute controller, Controller controller) => CanRoute controller where
    parseRoute' :: Parser controller
parseRoute' = Parser controller
forall controller.
(AutoRoute controller, ?context::RequestContext) =>
Parser controller
autoRoute
    {-# INLINABLE parseRoute' #-}

-- | Instances of the @QueryParam@ type class can be represented in URLs as query parameters.
-- Currently this is only Int, Text, and both wrapped in List and Maybe.
-- IDs also are representable in a URL, but we are unable to match on polymorphic types using reflection,
-- so we fall back to the default "show" for these.
class Data a => QueryParam a where
    showQueryParam :: a -> String

instance QueryParam Text where
    showQueryParam :: Text -> String
showQueryParam Text
text = Text -> String
Text.unpack Text
text

instance QueryParam Int where
    showQueryParam :: Int -> String
showQueryParam = Int -> String
forall a. Show a => a -> String
show

instance QueryParam Integer where
    showQueryParam :: Integer -> String
showQueryParam = Integer -> String
forall a. Show a => a -> String
show

instance QueryParam a => QueryParam (Maybe a) where
    showQueryParam :: Maybe a -> String
showQueryParam (Just a
val) = a -> String
forall a. QueryParam a => a -> String
showQueryParam a
val
    showQueryParam Maybe a
Nothing = String
""

instance QueryParam a => QueryParam [a] where
    showQueryParam :: [a] -> String
showQueryParam = String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
List.intercalate String
"," ([String] -> String) -> ([a] -> [String]) -> [a] -> String
forall k (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. (a -> String) -> [a] -> [String]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map a -> String
forall a. QueryParam a => a -> String
showQueryParam

instance {-# OVERLAPPABLE #-} (Show controller, AutoRoute controller) => HasPath controller where
    {-# INLINABLE pathTo #-}
    pathTo :: controller -> Text
pathTo !controller
action = String -> Text
Text.pack (String
appPrefix String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
actionName String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
arguments)
        where
            appPrefix :: String
            !appPrefix :: String
appPrefix = Typeable controller => String
forall controller. Typeable controller => String
actionPrefix @controller

            actionName :: String
            !actionName :: String
actionName = (String -> String
forall seq.
(IsSequence seq, IsString seq, Eq (Element seq)) =>
seq -> seq
stripActionSuffix (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$! Constr -> String
showConstr Constr
constructor)

            constructor :: Constr
constructor = controller -> Constr
forall a. Data a => a -> Constr
toConstr controller
action

            stripQuotes :: String -> String
stripQuotes (Char
'"':String
rest) = String -> String
forall a. [a] -> [a]
List.init String
rest
            stripQuotes String
otherwise = String
otherwise

            -- | The @gmapQ@ function allows us to iterate over each term in a constructor function and
            -- build a list of results from performing some function on each term.
            -- Here we send each term through @constrShow@, giving us our preferred representation for
            -- use in URLs.
            showTerms :: controller -> [Maybe String]
            showTerms :: controller -> [Maybe String]
showTerms = (forall d. Data d => d -> Maybe String)
-> controller -> [Maybe String]
forall a u. Data a => (forall d. Data d => d -> u) -> a -> [u]
gmapQ ([d -> Maybe String] -> d -> Maybe String
forall d. Data d => [d -> Maybe String] -> d -> Maybe String
constrShow [d -> Maybe String]
forall d. Data d => [d -> Maybe String]
typeShows)

            -- | @constrShow@ tries to convert each value @d@ into a String representation.
            -- If one passes, return it immediately, otherwise try all the defined @typeShow@ functions.
            constrShow :: Data d => [(d -> Maybe String)] -> d -> Maybe String
            constrShow :: [d -> Maybe String] -> d -> Maybe String
constrShow [] d
_ = Maybe String
forall a. Maybe a
Nothing
            constrShow (d -> Maybe String
f:[d -> Maybe String]
fs) d
d = case d -> Maybe String
f d
d of
                Just String
str -> String -> Maybe String
forall a. a -> Maybe a
Just String
str
                Maybe String
Nothing -> [d -> Maybe String] -> d -> Maybe String
forall d. Data d => [d -> Maybe String] -> d -> Maybe String
constrShow [d -> Maybe String]
fs d
d

            -- | Try and match some value to all of the types we can represent in a URL.
            -- Only type not contained in here is the "Id" type, since we cannot match
            -- on polymorphic types.
            typeShows :: forall d. Data d => [(d -> Maybe String)]
            typeShows :: [d -> Maybe String]
typeShows = [
                \d
val -> (Maybe (d :~: Text)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Text))
                    Maybe (d :~: Text)
-> ((d :~: Text) -> Maybe String) -> Maybe String
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \d :~: Text
Refl -> String -> Maybe String
forall a. a -> Maybe a
Just (d -> String
forall a. QueryParam a => a -> String
showQueryParam d
val),
                \d
val -> (Maybe (d :~: [Text])
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: [Text]))
                    Maybe (d :~: [Text])
-> ((d :~: [Text]) -> Maybe String) -> Maybe String
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \d :~: [Text]
Refl -> String -> Maybe String
forall a. a -> Maybe a
Just ([Text] -> String
forall a. QueryParam a => a -> String
showQueryParam (d
[Text]
val :: [Text])),
                \d
val -> (Maybe (d :~: Maybe Text)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Maybe Text))
                    Maybe (d :~: Maybe Text)
-> ((d :~: Maybe Text) -> Maybe String) -> Maybe String
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \d :~: Maybe Text
Refl -> String -> Maybe String
forall a. a -> Maybe a
Just (d -> String
forall a. QueryParam a => a -> String
showQueryParam d
val),
                \d
val -> (Maybe (d :~: Int)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Int))
                    Maybe (d :~: Int) -> ((d :~: Int) -> Maybe String) -> Maybe String
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \d :~: Int
Refl -> String -> Maybe String
forall a. a -> Maybe a
Just (d -> String
forall a. QueryParam a => a -> String
showQueryParam d
val),
                \d
val -> (Maybe (d :~: [Int])
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: [Int]))
                    Maybe (d :~: [Int])
-> ((d :~: [Int]) -> Maybe String) -> Maybe String
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \d :~: [Int]
Refl -> String -> Maybe String
forall a. a -> Maybe a
Just (d -> String
forall a. QueryParam a => a -> String
showQueryParam d
val),
                \d
val -> (Maybe (d :~: Maybe Int)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Maybe Int))
                    Maybe (d :~: Maybe Int)
-> ((d :~: Maybe Int) -> Maybe String) -> Maybe String
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \d :~: Maybe Int
Refl -> String -> Maybe String
forall a. a -> Maybe a
Just (d -> String
forall a. QueryParam a => a -> String
showQueryParam d
val),
                \d
val -> (Maybe (d :~: Integer)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Integer))
                    Maybe (d :~: Integer)
-> ((d :~: Integer) -> Maybe String) -> Maybe String
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \d :~: Integer
Refl -> String -> Maybe String
forall a. a -> Maybe a
Just (d -> String
forall a. QueryParam a => a -> String
showQueryParam d
val),
                \d
val -> (Maybe (d :~: [Integer])
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: [Integer]))
                    Maybe (d :~: [Integer])
-> ((d :~: [Integer]) -> Maybe String) -> Maybe String
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \d :~: [Integer]
Refl -> String -> Maybe String
forall a. a -> Maybe a
Just (d -> String
forall a. QueryParam a => a -> String
showQueryParam d
val),
                \d
val -> (Maybe (d :~: Maybe Integer)
forall k (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT :: Maybe (d :~: Maybe Integer))
                    Maybe (d :~: Maybe Integer)
-> ((d :~: Maybe Integer) -> Maybe String) -> Maybe String
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \d :~: Maybe Integer
Refl -> String -> Maybe String
forall a. a -> Maybe a
Just (d -> String
forall a. QueryParam a => a -> String
showQueryParam d
val)

                ]

            arguments :: String
            !arguments :: String
arguments  = controller -> String
forall a. Show a => a -> String
show controller
action -- `SomeRecord { a = b, c = d }`
                    String -> (String -> String) -> String
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
List.filter (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
' ')
                    String -> (String -> (String, String)) -> (String, String)
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
List.break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'{')
                    (String, String) -> ((String, String) -> String) -> String
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> (String, String) -> String
forall a b. (a, b) -> b
snd
                    String -> (String -> String) -> String
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> Int -> String -> String
forall a. Int -> [a] -> [a]
List.drop Int
1
                    String -> (String -> (String, String)) -> (String, String)
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
List.break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'}')
                    (String, String) -> ((String, String) -> String) -> String
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> (String, String) -> String
forall a b. (a, b) -> a
fst -- `a=b,c=d`
                    String -> (String -> [String]) -> [String]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> (Char -> Bool) -> String -> [String]
forall a. (a -> Bool) -> [a] -> [[a]]
List.splitWhen (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
',') -- ["a=b", "c=d"]
                    [String] -> ([String] -> [(String, String)]) -> [(String, String)]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> (String -> (String, String)) -> [String] -> [(String, String)]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map (\String
s -> let (String
key, String
value) = (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
List.break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'=') String
s in (String
key, Int -> String -> String
forall a. Int -> [a] -> [a]
List.drop Int
1 String
value))
                    [(String, String)]
-> ([(String, String)] -> [(String, String)]) -> [(String, String)]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> ((String, String) -> (String, String))
-> [(String, String)] -> [(String, String)]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map (\(String
k ,String
v) -> (String
k, String -> String
stripQuotes String
v)) -- "value" -> value
                    [(String, String)]
-> ([(String, String)] -> [(String, String)]) -> [(String, String)]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> (Element [(String, String)] -> Bool)
-> [(String, String)] -> [(String, String)]
forall seq. IsSequence seq => (Element seq -> Bool) -> seq -> seq
filter (\(k, v) -> (Bool -> Bool
not (Bool -> Bool) -> (String -> Bool) -> String -> Bool
forall k (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
List.null) String
k Bool -> Bool -> Bool
&& (Bool -> Bool
not (Bool -> Bool) -> (String -> Bool) -> String -> Bool
forall k (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
List.null) String
v)
                    -- At this point we have a list of keys and values as represented by @show@.
                    -- For Lists and Maybe types, we want to represent these in a different way,
                    -- so we construct another list of values using type reflection and the QueryParam type class.
                    [(String, String)] -> ([(String, String)] -> String) -> String
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> \([(String, String)]
kvs :: [(String, String)]) -> [Maybe String]
-> [(String, String)] -> [(Maybe String, (String, String))]
forall (f :: * -> *) a b. Zip f => f a -> f b -> f (a, b)
zip (controller -> [Maybe String]
showTerms controller
action) [(String, String)]
kvs
                    -- If an Id type was present in the action, it will be returned as Nothing by @showTerms@
                    -- as we are not able to match on the type using reflection.
                    -- In this case we default back to the @show@ representation.
                    [(Maybe String, (String, String))]
-> ([(Maybe String, (String, String))] -> [(String, String)])
-> [(String, String)]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> ((Maybe String, (String, String)) -> (String, String))
-> [(Maybe String, (String, String))] -> [(String, String)]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map (\(Maybe String
v1, (String
k, String
v2)) -> (String
k, String -> Maybe String -> String
forall a. a -> Maybe a -> a
fromMaybe String
v2 Maybe String
v1))
                    [(String, String)] -> ([(String, String)] -> [String]) -> [String]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> ((String, String) -> String) -> [(String, String)] -> [String]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map (\(String
k, String
v) -> if String -> Bool
forall value. IsEmpty value => value -> Bool
isEmpty String
v
                        then String
""
                        else  String
k String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
"=" String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String -> String
URI.encode String
v)
                    [String] -> ([String] -> [String]) -> [String]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
List.filter (Bool -> Bool
not (Bool -> Bool) -> (String -> Bool) -> String -> Bool
forall k (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. String -> Bool
forall value. IsEmpty value => value -> Bool
isEmpty)
                    [String] -> ([String] -> String) -> String
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
List.intercalate String
"&"
                    String -> (String -> String) -> String
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> (\String
q -> if String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
List.null String
q then String
q else Char
'?'Char -> String -> String
forall a. a -> [a] -> [a]
:String
q)

-- | Parses the HTTP Method from the request and returns it.
getMethod :: (?context :: RequestContext) => Parser StdMethod
getMethod :: Parser StdMethod
getMethod =
        ?context::RequestContext
RequestContext
?context
        RequestContext -> (RequestContext -> Request) -> Request
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> RequestContext -> Request
IHP.Controller.RequestContext.request
        Request -> (Request -> ByteString) -> ByteString
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> Request -> ByteString
requestMethod
        ByteString
-> (ByteString -> Either ByteString StdMethod)
-> Either ByteString StdMethod
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> ByteString -> Either ByteString StdMethod
parseMethod
        Either ByteString StdMethod
-> (Either ByteString StdMethod -> Parser StdMethod)
-> Parser StdMethod
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> \case
            Left ByteString
error -> String -> Parser StdMethod
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (ByteString -> String
ByteString.unpack ByteString
error)
            Right StdMethod
method -> StdMethod -> Parser StdMethod
forall (f :: * -> *) a. Applicative f => a -> f a
pure StdMethod
method
{-# INLINABLE getMethod #-}

-- | Routes a given path to an action when requested via GET.
--
-- __Example:__
--
-- > instance FrontController WebApplication where
-- >     controllers = [
-- >             get "/my-custom-page" NewSessionAction
-- >         ]
--
-- The request @GET \/my-custom-page@ is now executing NewSessionAction
--
-- Also see 'post'.
get :: (Controller action
    , InitControllerContext application
    , ?application :: application
    , ?applicationContext :: ApplicationContext
    , ?context :: RequestContext
    , Typeable application
    , Typeable action
    ) => ByteString -> action -> Parser (IO ResponseReceived)
get :: ByteString -> action -> Parser (IO ResponseReceived)
get ByteString
path action
action = do
    StdMethod
method <- Parser StdMethod
(?context::RequestContext) => Parser StdMethod
getMethod
    case StdMethod
method of
        StdMethod
GET -> do
            ByteString -> Parser ByteString
string ByteString
path
            IO ResponseReceived -> Parser (IO ResponseReceived)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (action -> IO ResponseReceived
forall application controller.
(Controller controller, ?applicationContext::ApplicationContext,
 ?context::RequestContext, InitControllerContext application,
 ?application::application, Typeable application,
 Typeable controller) =>
controller -> IO ResponseReceived
runActionWithNewContext action
action)
        StdMethod
_   -> String -> Parser (IO ResponseReceived)
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Invalid method, expected GET"
{-# INLINABLE get #-}

-- | Routes a given path to an action when requested via POST.
--
-- __Example:__
--
-- > instance FrontController WebApplication where
-- >     controllers = [
-- >             post "/do-something" DoSomethingAction
-- >         ]
--
-- The request @POST \/do-something@ is now executing DoSomethingAction
--
-- Also see 'get'.
post :: (Controller action
    , InitControllerContext application
    , ?application :: application
    , ?applicationContext :: ApplicationContext
    , ?context :: RequestContext
    , Typeable application
    , Typeable action
    ) => ByteString -> action -> Parser (IO ResponseReceived)
post :: ByteString -> action -> Parser (IO ResponseReceived)
post ByteString
path action
action = do
    StdMethod
method <- Parser StdMethod
(?context::RequestContext) => Parser StdMethod
getMethod
    case StdMethod
method of
        StdMethod
POST -> do
            ByteString -> Parser ByteString
string ByteString
path
            IO ResponseReceived -> Parser (IO ResponseReceived)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (action -> IO ResponseReceived
forall application controller.
(Controller controller, ?applicationContext::ApplicationContext,
 ?context::RequestContext, InitControllerContext application,
 ?application::application, Typeable application,
 Typeable controller) =>
controller -> IO ResponseReceived
runActionWithNewContext action
action)
        StdMethod
_   -> String -> Parser (IO ResponseReceived)
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Invalid method, expected POST"
{-# INLINABLE post #-}

-- | Routes to a given WebSocket app if the path matches the WebSocket app name
--
-- __Example:__
--
-- > instance FrontController WebApplication where
-- >     controllers = [
-- >             webSocketApp @AutoRefreshWSApp
-- >         ]
--
-- The request @\/AutoRefreshWSApp@ will call the AutoRefreshWSApp
--
webSocketApp :: forall webSocketApp application.
    ( WSApp webSocketApp
    , InitControllerContext application
    , ?application :: application
    , ?applicationContext :: ApplicationContext
    , ?context :: RequestContext
    , Typeable application
    , Typeable webSocketApp
    ) => Parser (IO ResponseReceived)
webSocketApp :: Parser (IO ResponseReceived)
webSocketApp = ByteString -> Parser (IO ResponseReceived)
forall webSocketApp application.
(WSApp webSocketApp, InitControllerContext application,
 ?application::application, ?applicationContext::ApplicationContext,
 ?context::RequestContext, Typeable application,
 Typeable webSocketApp) =>
ByteString -> Parser (IO ResponseReceived)
webSocketAppWithCustomPath @webSocketApp ByteString
typeName
    where
        typeName :: ByteString
        typeName :: ByteString
typeName = webSocketApp -> TypeRep
forall a. Typeable a => a -> TypeRep
Typeable.typeOf (String -> webSocketApp
forall a. HasCallStack => String -> a
error String
"unreachable" :: webSocketApp)
                TypeRep -> (TypeRep -> String) -> String
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> TypeRep -> String
forall a. Show a => a -> String
show
                String -> (String -> ByteString) -> ByteString
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> String -> ByteString
ByteString.pack
{-# INLINABLE webSocketApp #-}

-- | Routes to a given WebSocket app if the path matches
--
-- __Example:__
--
-- > instance FrontController WebApplication where
-- >     controllers = [
-- >             webSocketAppWithCustomPath @AutoRefreshWSApp "my-ws-app"
-- >         ]
--
-- The request @\/my-ws-app@ will call the AutoRefreshWSApp
--
webSocketAppWithCustomPath :: forall webSocketApp application.
    ( WSApp webSocketApp
    , InitControllerContext application
    , ?application :: application
    , ?applicationContext :: ApplicationContext
    , ?context :: RequestContext
    , Typeable application
    , Typeable webSocketApp
    ) => ByteString -> Parser (IO ResponseReceived)
webSocketAppWithCustomPath :: ByteString -> Parser (IO ResponseReceived)
webSocketAppWithCustomPath ByteString
path = do
        Char -> Parser Char
Attoparsec.char Char
'/'
        ByteString -> Parser ByteString
string ByteString
path
        IO ResponseReceived -> Parser (IO ResponseReceived)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (forall application.
(?applicationContext::ApplicationContext, ?context::RequestContext,
 InitControllerContext application, ?application::application,
 Typeable application, WSApp webSocketApp) =>
IO ResponseReceived
forall webSocketApp application.
(?applicationContext::ApplicationContext, ?context::RequestContext,
 InitControllerContext application, ?application::application,
 Typeable application, WSApp webSocketApp) =>
IO ResponseReceived
startWebSocketApp @webSocketApp)
{-# INLINABLE webSocketAppWithCustomPath #-}

-- | Defines the start page for a router (when @\/@ is requested).
startPage :: forall action application. (Controller action, InitControllerContext application, ?application::application, ?applicationContext::ApplicationContext, ?context::RequestContext, Typeable application, Typeable action) => action -> Parser (IO ResponseReceived)
startPage :: action -> Parser (IO ResponseReceived)
startPage action
action = ByteString -> action -> Parser (IO ResponseReceived)
forall action application.
(Controller action, InitControllerContext application,
 ?application::application, ?applicationContext::ApplicationContext,
 ?context::RequestContext, Typeable application, Typeable action) =>
ByteString -> action -> Parser (IO ResponseReceived)
get (String -> ByteString
ByteString.pack (Typeable action => String
forall controller. Typeable controller => String
actionPrefix @action)) action
action
{-# INLINABLE startPage #-}

withPrefix :: ByteString -> [Parser ByteString b] -> Parser ByteString b
withPrefix ByteString
prefix [Parser ByteString b]
routes = ByteString -> Parser ByteString
string ByteString
prefix Parser ByteString -> Parser ByteString b -> Parser ByteString b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> [Parser ByteString b] -> Parser ByteString b
forall (f :: * -> *) a. Alternative f => [f a] -> f a
choice ((Parser ByteString b -> Parser ByteString b)
-> [Parser ByteString b] -> [Parser ByteString b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map (\Parser ByteString b
r -> Parser ByteString b
r Parser ByteString b -> Parser ByteString () -> Parser ByteString b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Parser ByteString ()
forall t. Chunk t => Parser t ()
endOfInput) [Parser ByteString b]
routes)
{-# INLINABLE withPrefix #-}

runApp :: (?applicationContext :: ApplicationContext, ?context :: RequestContext) => Parser (IO ResponseReceived) -> IO ResponseReceived -> IO ResponseReceived
runApp :: Parser (IO ResponseReceived)
-> IO ResponseReceived -> IO ResponseReceived
runApp Parser (IO ResponseReceived)
routes IO ResponseReceived
notFoundAction = do
    let path :: ByteString
path = ?context::RequestContext
RequestContext
?context
                RequestContext -> (RequestContext -> Request) -> Request
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> forall k (x :: k) r a. HasField x r a => r -> a
forall r a. HasField "request" r a => r -> a
getField @"request"
                Request -> (Request -> ByteString) -> ByteString
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> Request -> ByteString
rawPathInfo
        handleException :: SomeException -> f (Either a (IO ResponseReceived))
handleException SomeException
exception = Either a (IO ResponseReceived)
-> f (Either a (IO ResponseReceived))
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either a (IO ResponseReceived)
 -> f (Either a (IO ResponseReceived)))
-> Either a (IO ResponseReceived)
-> f (Either a (IO ResponseReceived))
forall a b. (a -> b) -> a -> b
$ IO ResponseReceived -> Either a (IO ResponseReceived)
forall a b. b -> Either a b
Right ((?context::RequestContext) => SomeException -> IO ResponseReceived
SomeException -> IO ResponseReceived
ErrorController.handleRouterException SomeException
exception)

    Either String (IO ResponseReceived)
routedAction <- (Either String (IO ResponseReceived)
-> IO (Either String (IO ResponseReceived))
forall (m :: * -> *) a. MonadIO m => a -> m a
evaluate (Either String (IO ResponseReceived)
 -> IO (Either String (IO ResponseReceived)))
-> Either String (IO ResponseReceived)
-> IO (Either String (IO ResponseReceived))
forall a b. (a -> b) -> a -> b
$ Parser (IO ResponseReceived)
-> ByteString -> Either String (IO ResponseReceived)
forall a. Parser a -> ByteString -> Either String a
parseOnly (Parser (IO ResponseReceived)
routes Parser (IO ResponseReceived)
-> Parser ByteString () -> Parser (IO ResponseReceived)
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Parser ByteString ()
forall t. Chunk t => Parser t ()
endOfInput) ByteString
path) IO (Either String (IO ResponseReceived))
-> (SomeException -> IO (Either String (IO ResponseReceived)))
-> IO (Either String (IO ResponseReceived))
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`Exception.catch` SomeException -> IO (Either String (IO ResponseReceived))
forall (f :: * -> *) a.
(Applicative f, ?context::RequestContext) =>
SomeException -> f (Either a (IO ResponseReceived))
handleException
    case Either String (IO ResponseReceived)
routedAction of
        Left String
message -> IO ResponseReceived
notFoundAction
        Right IO ResponseReceived
action -> IO ResponseReceived
action
{-# INLINABLE runApp #-}

frontControllerToWAIApp :: forall app parent config controllerContext. (?applicationContext :: ApplicationContext, ?context :: RequestContext, FrontController app) => app -> [Parser (IO ResponseReceived)] -> IO ResponseReceived -> IO ResponseReceived
frontControllerToWAIApp :: app
-> [Parser (IO ResponseReceived)]
-> IO ResponseReceived
-> IO ResponseReceived
frontControllerToWAIApp app
application [Parser (IO ResponseReceived)]
additionalControllers IO ResponseReceived
notFoundAction = (?applicationContext::ApplicationContext,
 ?context::RequestContext) =>
Parser (IO ResponseReceived)
-> IO ResponseReceived -> IO ResponseReceived
Parser (IO ResponseReceived)
-> IO ResponseReceived -> IO ResponseReceived
runApp ([Parser (IO ResponseReceived)] -> Parser (IO ResponseReceived)
forall (f :: * -> *) a. Alternative f => [f a] -> f a
choice ((Parser (IO ResponseReceived) -> Parser (IO ResponseReceived))
-> [Parser (IO ResponseReceived)] -> [Parser (IO ResponseReceived)]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map (\Parser (IO ResponseReceived)
r -> Parser (IO ResponseReceived)
r Parser (IO ResponseReceived)
-> Parser ByteString () -> Parser (IO ResponseReceived)
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Parser ByteString ()
forall t. Chunk t => Parser t ()
endOfInput) [Parser (IO ResponseReceived)]
allControllers)) IO ResponseReceived
notFoundAction
    where
        allControllers :: [Parser (IO ResponseReceived)]
allControllers = (let ?application = application in [Parser (IO ResponseReceived)]
forall application.
(FrontController application,
 ?applicationContext::ApplicationContext, ?application::application,
 ?context::RequestContext) =>
[Parser (IO ResponseReceived)]
controllers) [Parser (IO ResponseReceived)]
-> [Parser (IO ResponseReceived)] -> [Parser (IO ResponseReceived)]
forall a. Semigroup a => a -> a -> a
<> [Parser (IO ResponseReceived)]
additionalControllers
{-# INLINABLE frontControllerToWAIApp #-}

mountFrontController :: forall frontController application. (?applicationContext :: ApplicationContext, ?context :: RequestContext, FrontController frontController) => frontController -> Parser (IO ResponseReceived)
mountFrontController :: frontController -> Parser (IO ResponseReceived)
mountFrontController frontController
application = let ?application = application in [Parser (IO ResponseReceived)] -> Parser (IO ResponseReceived)
forall (f :: * -> *) a. Alternative f => [f a] -> f a
choice ((Parser (IO ResponseReceived) -> Parser (IO ResponseReceived))
-> [Parser (IO ResponseReceived)] -> [Parser (IO ResponseReceived)]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map (\Parser (IO ResponseReceived)
r -> Parser (IO ResponseReceived)
r Parser (IO ResponseReceived)
-> Parser ByteString () -> Parser (IO ResponseReceived)
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Parser ByteString ()
forall t. Chunk t => Parser t ()
endOfInput) [Parser (IO ResponseReceived)]
forall application.
(FrontController application,
 ?applicationContext::ApplicationContext, ?application::application,
 ?context::RequestContext) =>
[Parser (IO ResponseReceived)]
controllers)
{-# INLINABLE mountFrontController #-}

parseRoute :: forall controller application. (?applicationContext :: ApplicationContext, ?context :: RequestContext, Controller controller, CanRoute controller, InitControllerContext application, ?application :: application, Typeable application, Data controller) => Parser (IO ResponseReceived)
parseRoute :: Parser (IO ResponseReceived)
parseRoute = do
    controller
action <- (CanRoute controller, ?context::RequestContext) =>
Parser controller
forall controller.
(CanRoute controller, ?context::RequestContext) =>
Parser controller
parseRoute' @controller
    IO ResponseReceived -> Parser (IO ResponseReceived)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (controller -> IO ResponseReceived
forall application controller.
(Controller controller, ?applicationContext::ApplicationContext,
 ?context::RequestContext, InitControllerContext application,
 ?application::application, Typeable application,
 Typeable controller) =>
controller -> IO ResponseReceived
runActionWithNewContext @application controller
action)
{-# INLINABLE parseRoute #-}

parseUUIDOrTextId ::  ByteString -> Maybe Dynamic
parseUUIDOrTextId :: ByteString -> Maybe Dynamic
parseUUIDOrTextId ByteString
queryVal = ByteString
queryVal
    ByteString -> (ByteString -> Maybe UUID) -> Maybe UUID
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> ByteString -> Maybe UUID
fromASCIIBytes
    Maybe UUID -> (Maybe UUID -> Maybe Dynamic) -> Maybe Dynamic
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> \case
        Just UUID
uuid -> UUID
uuid UUID -> (UUID -> Dynamic) -> Dynamic
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> UUID -> Dynamic
forall a. Typeable a => a -> Dynamic
toDyn Dynamic -> (Dynamic -> Maybe Dynamic) -> Maybe Dynamic
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> Dynamic -> Maybe Dynamic
forall a. a -> Maybe a
Just
        Maybe UUID
Nothing -> Maybe Dynamic
forall a. Maybe a
Nothing

parseRouteWithId
    :: forall controller application.
        (?applicationContext :: ApplicationContext,
            ?context :: RequestContext,
            Controller controller,
            CanRoute controller,
            InitControllerContext application,
            ?application :: application,
            Typeable application,
            Data controller)
        => Parser (IO ResponseReceived)
parseRouteWithId :: Parser (IO ResponseReceived)
parseRouteWithId = do
    controller
action <- (CanRoute controller, ?context::RequestContext) =>
Parser controller
forall controller.
(CanRoute controller, ?context::RequestContext) =>
Parser controller
parseRoute' @controller
    IO ResponseReceived -> Parser (IO ResponseReceived)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (controller -> IO ResponseReceived
forall application controller.
(Controller controller, ?applicationContext::ApplicationContext,
 ?context::RequestContext, InitControllerContext application,
 ?application::application, Typeable application,
 Typeable controller) =>
controller -> IO ResponseReceived
runActionWithNewContext @application controller
action)

catchAll :: forall action application. (?applicationContext :: ApplicationContext, ?context :: RequestContext, Controller action, InitControllerContext application, Typeable action, ?application :: application, Typeable application, Data action) => action -> Parser (IO ResponseReceived)
catchAll :: action -> Parser (IO ResponseReceived)
catchAll action
action = do
    ByteString -> Parser ByteString
string (String -> ByteString
ByteString.pack (Typeable action => String
forall controller. Typeable controller => String
actionPrefix @action))
    ByteString
_ <- Parser ByteString
takeByteString
    IO ResponseReceived -> Parser (IO ResponseReceived)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (action -> IO ResponseReceived
forall application controller.
(Controller controller, ?applicationContext::ApplicationContext,
 ?context::RequestContext, InitControllerContext application,
 ?application::application, Typeable application,
 Typeable controller) =>
controller -> IO ResponseReceived
runActionWithNewContext @application action
action)
{-# INLINABLE catchAll #-}

-- | This instances makes it possible to write @<a href={MyAction}/>@ in HSX
instance {-# OVERLAPPABLE #-} (HasPath action) => ConvertibleStrings action Html5.AttributeValue where
    convertString :: action -> AttributeValue
convertString action
action = Text -> AttributeValue
Html5.textValue (action -> Text
forall controller. HasPath controller => controller -> Text
pathTo action
action)
    {-# INLINE convertString #-}

-- | Parses and returns an UUID
parseUUID :: Parser UUID
parseUUID :: Parser UUID
parseUUID = do
        ByteString
uuid <- Int -> Parser ByteString
take Int
36
        case ByteString -> Maybe UUID
fromASCIIBytes ByteString
uuid of
            Just UUID
theUUID -> UUID -> Parser UUID
forall (f :: * -> *) a. Applicative f => a -> f a
pure UUID
theUUID
            Maybe UUID
Nothing -> String -> Parser UUID
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"not uuid"
{-# INLINABLE parseUUID #-}

-- | Parses an UUID, afterwards wraps it in an Id
parseId :: ((ModelSupport.PrimaryKey table) ~ UUID) => Parser (ModelSupport.Id' table)
parseId :: Parser (Id' table)
parseId = UUID -> Id' table
forall (table :: Symbol). PrimaryKey table -> Id' table
ModelSupport.Id (UUID -> Id' table) -> Parser UUID -> Parser (Id' table)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Parser UUID
parseUUID
{-# INLINABLE parseId #-}

-- | Returns all the remaining text until the end of the input
remainingText :: Parser Text
remainingText :: Parser Text
remainingText = ByteString -> Text
Text.decodeUtf8 (ByteString -> Text) -> Parser ByteString -> Parser Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Parser ByteString
takeByteString
{-# INLINABLE remainingText #-}

-- | Parses until the next @/@
parseText :: Parser Text
parseText :: Parser Text
parseText = ByteString -> Text
Text.decodeUtf8 (ByteString -> Text) -> Parser ByteString -> Parser Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Char -> Bool) -> Parser ByteString
takeTill (Char
'/' Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
==)
{-# INLINABLE parseText #-}

parseIntegerId :: (Data idType) => ByteString -> Maybe idType
parseIntegerId :: ByteString -> Maybe idType
parseIntegerId ByteString
queryVal = let
    Maybe Integer
rawValue :: Maybe Integer = String -> Maybe Integer
forall c a.
(Element c ~ Char, MonoFoldable c, Read a) =>
c -> Maybe a
readMay (ByteString -> String
forall a b. ConvertibleStrings a b => a -> b
cs ByteString
queryVal :: String)
    in
       Maybe Integer
rawValue Maybe Integer -> (Integer -> Maybe idType) -> Maybe idType
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= idType -> Maybe idType
forall a. a -> Maybe a
Just (idType -> Maybe idType)
-> (Integer -> idType) -> Integer -> Maybe idType
forall k (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. Integer -> idType
forall a b. a -> b
unsafeCoerce


-- | Display a better error when the user missed to pass an argument to an action.
--
-- E.g. when you forgot to pass a projectId to the ShowProjectAction:
--
-- > <a href={ShowProjectAction}>Show project</a>
--
-- The correct code would be this:
--
-- > <a href={ShowProjectAction projectId}>Show project</a>
--
-- See https://forum.ihpapp.com/ShowThread?threadId=ad73d6a5-2481-4e2f-af46-9bf8849f998b
-- See https://github.com/digitallyinduced/ihp/issues/840
instance ((T.TypeError (T.Text "Looks like you forgot to pass a " :<>: (T.ShowType argument) :<>: T.Text " to this " :<>: (T.ShowType controller))), Data argument, Data controller) => AutoRoute (argument -> controller) where