@@ -1,67 +1,50 @@
1−{-# LANGUAGE ConstraintKinds #-}
21{-# LANGUAGE CPP #-}
3−{-# LANGUAGE DataKinds #-}
42{-# LANGUAGE DefaultSignatures #-}
53{-# LANGUAGE DeriveGeneric #-}
64{-# LANGUAGE FlexibleContexts #-}
75{-# LANGUAGE FlexibleInstances #-}
86{-# LANGUAGE GeneralizedNewtypeDeriving #-}
97{-# LANGUAGE KindSignatures #-}
10−{-# LANGUAGE MultiParamTypeClasses #-}
118{-# LANGUAGE OverloadedStrings #-}
129{-# LANGUAGE PolyKinds #-}
1310{-# LANGUAGE ScopedTypeVariables #-}
1411{-# LANGUAGE TypeFamilies #-}
1512{-# LANGUAGE TypeOperators #-}
16−{-# LANGUAGE UndecidableInstances #-}
17−#include "overlapping-compat.h"
1813module Web.Internal.FormUrlEncoded where
1914
20−import Prelude ()
21−import Prelude.Compat
15+#if __GLASGOW_HASKELL__ < 710
16+import Control.Applicative
17+#endif
2218
23−import Control.Applicative (Const(Const))
2419import Control.Arrow ((***))
2520import Control.Monad ((<=<))
26−import Data.ByteString.Builder (shortByteString, toLazyByteString)
2721import qualified Data.ByteString.Lazy as BSL
2822import qualified Data.ByteString.Lazy.Char8 as BSL8
29−import Data.Coerce (coerce)
30−import qualified Data.Foldable as F
31−import Data.Functor.Identity (Identity(Identity))
3223import Data.Hashable (Hashable)
3324import Data.HashMap.Strict (HashMap)
3425import qualified Data.HashMap.Strict as HashMap
35−import Data.Int (Int16, Int32, Int64, Int8)
26+import Data.Int
3627import Data.IntMap (IntMap)
3728import qualified Data.IntMap as IntMap
38−import Data.List (intersperse, sortBy)
3929import Data.Map (Map)
4030import qualified Data.Map as Map
41−import Data.Monoid (All (..), Any (..), Dual (..),
42− Product (..), Sum (..))
43−import Data.Ord (comparing)
44−import Data.Proxy (Proxy (..))
45−import Data.Semigroup (Semigroup (..))
46−import qualified Data.Semigroup as Semi
47−import Data.Tagged (Tagged (..))
31+import Data.Monoid
32+
4833import Data.Text (Text)
4934import qualified Data.Text as Text
50−import qualified Data.Text.Encoding as Text
51−import Data.Text.Encoding.Error (lenientDecode)
5235import qualified Data.Text.Lazy as Lazy
53−import Data.Time.Compat (Day, LocalTime, NominalDiffTime,
54− UTCTime, ZonedTime)
55−import Data.Time.Calendar.Month.Compat (Month)
56−import Data.Time.Calendar.Quarter.Compat (Quarter, QuarterOfYear (..))
57−import Data.Void (Void)
58−import Data.Word (Word16, Word32, Word64, Word8)
59−import GHC.Exts (Constraint, IsList (..))
36+import Data.Text.Encoding as Text
37+import Data.Text.Encoding.Error (lenientDecode)
38+
39+import Data.Time
40+import Data.Word
41+
42+import GHC.Exts (IsList (..))
6043import GHC.Generics
61−import GHC.TypeLits
62−import Network.HTTP.Types.URI (urlDecode, urlEncodeBuilder)
63−import Numeric.Natural (Natural)
64−import Web.Internal.HttpApiData
44+import Network.URI (escapeURIString, isUnreserved,
45+ unEscapeString)
46+
47+import Web.Internal.HttpApiData
6548
6649-- $setup
6750-- >>> :set -XDeriveGeneric
@@ -70,20 +53,11 @@ import Web.Internal.HttpApiData
7053-- >>> :set -XFlexibleContexts
7154-- >>> :set -XScopedTypeVariables
7255-- >>> :set -XTypeFamilies
73−-- >>> import Data.Char (toLower)
74−--
56+-- >>> import Data.Either (isLeft)
57+-- >>> import Data.List (sort)
7558-- >>> data Person = Person { name :: String, age :: Int } deriving (Show, Generic)
7659-- >>> instance ToForm Person
7760-- >>> instance FromForm Person
78−--
79−-- >>> data Post = Post { title :: String, subtitle :: Maybe String, comments :: [String]} deriving (Generic, Show)
80−-- >>> instance ToForm Post
81−-- >>> instance FromForm Post
82−--
83−-- >>> data Project = Project { projectName :: String, projectSize :: Int } deriving (Generic, Show)
84−-- >>> let myOptions = FormOptions { fieldLabelModifier = map toLower . drop (length ("project" :: String)) }
85−-- >>> instance ToForm Project where toForm = genericToForm myOptions
86−-- >>> instance FromForm Project where fromForm = genericFromForm myOptions
8761
8862-- | Typeclass for types that can be used as keys in a 'Form'-like container (like 'Map').
8963class ToFormKey k where
@@ -115,9 +89,6 @@ instance ToFormKey LocalTime where toFormKey = toQueryParam
11589instance ToFormKey ZonedTime where toFormKey = toQueryParam
11690instance ToFormKey UTCTime where toFormKey = toQueryParam
11791instance ToFormKey NominalDiffTime where toFormKey = toQueryParam
118−instance ToFormKey Quarter where toFormKey = toQueryParam
119−instance ToFormKey QuarterOfYear where toFormKey = toQueryParam
120−instance ToFormKey Month where toFormKey = toQueryParam
12192
12293instance ToFormKey String where toFormKey = toQueryParam
12394instance ToFormKey Text where toFormKey = toQueryParam
@@ -126,26 +97,9 @@ instance ToFormKey Lazy.Text where toFormKey = toQueryParam
12697instance ToFormKey All where toFormKey = toQueryParam
12798instance ToFormKey Any where toFormKey = toQueryParam
12899
129−instance ToFormKey a => ToFormKey (Dual a) where toFormKey = coerce (toFormKey :: a -> Text)
130−instance ToFormKey a => ToFormKey (Sum a) where toFormKey = coerce (toFormKey :: a -> Text)
131−instance ToFormKey a => ToFormKey (Product a) where toFormKey = coerce (toFormKey :: a -> Text)
132−
133−instance ToFormKey a => ToFormKey (Semi.Min a) where toFormKey = coerce (toFormKey :: a -> Text)
134−instance ToFormKey a => ToFormKey (Semi.Max a) where toFormKey = coerce (toFormKey :: a -> Text)
135−instance ToFormKey a => ToFormKey (Semi.First a) where toFormKey = coerce (toFormKey :: a -> Text)
136−instance ToFormKey a => ToFormKey (Semi.Last a) where toFormKey = coerce (toFormKey :: a -> Text)
137−
138−instance ToFormKey a => ToFormKey (Tagged b a) where toFormKey = coerce (toFormKey :: a -> Text)
139−
140−-- | @since 0.4.2
141−instance ToFormKey a => ToFormKey (Identity a) where toFormKey = coerce (toFormKey :: a -> Text)
142−
143−-- | @since 0.4.2
144−instance ToFormKey a => ToFormKey (Const a b) where
145− toFormKey = coerce (toFormKey :: a -> Text)
146−
147−instance ToFormKey Void where toFormKey = toQueryParam
148−instance ToFormKey Natural where toFormKey = toQueryParam
100+instance ToFormKey a => ToFormKey (Dual a) where toFormKey = toFormKey . getDual
101+instance ToFormKey a => ToFormKey (Sum a) where toFormKey = toFormKey . getSum
102+instance ToFormKey a => ToFormKey (Product a) where toFormKey = toFormKey . getProduct
149103
150104-- | Typeclass for types that can be parsed from keys of a 'Form'. This is the reverse of 'ToFormKey'.
151105class FromFormKey k where
@@ -177,9 +131,6 @@ instance FromFormKey LocalTime where parseFormKey = parseQueryParam
177131instance FromFormKey ZonedTime where parseFormKey = parseQueryParam
178132instance FromFormKey UTCTime where parseFormKey = parseQueryParam
179133instance FromFormKey NominalDiffTime where parseFormKey = parseQueryParam
180−instance FromFormKey Quarter where parseFormKey = parseQueryParam
181−instance FromFormKey QuarterOfYear where parseFormKey = parseQueryParam
182−instance FromFormKey Month where parseFormKey = parseQueryParam
183134
184135instance FromFormKey String where parseFormKey = parseQueryParam
185136instance FromFormKey Text where parseFormKey = parseQueryParam
@@ -188,48 +139,25 @@ instance FromFormKey Lazy.Text where parseFormKey = parseQueryParam
188139instance FromFormKey All where parseFormKey = parseQueryParam
189140instance FromFormKey Any where parseFormKey = parseQueryParam
190141
191−instance FromFormKey a => FromFormKey (Dual a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
192−instance FromFormKey a => FromFormKey (Sum a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
193−instance FromFormKey a => FromFormKey (Product a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
194−
195−instance FromFormKey a => FromFormKey (Semi.Min a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
196−instance FromFormKey a => FromFormKey (Semi.Max a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
197−instance FromFormKey a => FromFormKey (Semi.First a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
198−instance FromFormKey a => FromFormKey (Semi.Last a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
199−
200−instance FromFormKey a => FromFormKey (Tagged b a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
201−
202−-- | @since 0.4.2
203−instance FromFormKey a => FromFormKey (Identity a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
204−
205−-- | @since 0.4.2
206−instance FromFormKey a => FromFormKey (Const a b) where
207− parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
208−
209−instance FromFormKey Void where parseFormKey = parseQueryParam
210−instance FromFormKey Natural where parseFormKey = parseQueryParam
142+instance FromFormKey a => FromFormKey (Dual a) where parseFormKey = fmap Dual . parseFormKey
143+instance FromFormKey a => FromFormKey (Sum a) where parseFormKey = fmap Sum . parseFormKey
144+instance FromFormKey a => FromFormKey (Product a) where parseFormKey = fmap Product . parseFormKey
211145
212146-- | The contents of a form, not yet URL-encoded.
213147--
214−-- 'Form' can be URL-encoded with 'urlEncodeForm' and URL-decoded with 'urlDecodeForm'.
148+-- 'Form' can be URL-encoded with 'encodeForm' and URL-decoded with 'decodeForm'.
215149newtype Form = Form { unForm :: HashMap Text [Text] }
216− deriving (Eq, Read, Generic, Semigroup, Monoid)
150+ deriving (Eq, Read, Generic, Monoid)
217151
218152instance Show Form where
219153 showsPrec d form = showParen (d > 10) $
220− showString "fromList " . shows (toListStable form)
154+ showString "fromList " . shows (toList form)
221155
222−-- | _NOTE:_ 'toList' is unstable and may result in different key order (but not values).
223−-- For a stable conversion use 'toListStable'.
224156instance IsList Form where
225157 type Item Form = (Text, Text)
226158 fromList = Form . HashMap.fromListWith (flip (<>)) . fmap (\(k, v) -> (k, [v]))
227159 toList = concatMap (\(k, vs) -> map ((,) k) vs) . HashMap.toList . unForm
228160
229−-- | A stable version of 'toList'.
230−toListStable :: Form -> [(Text, Text)]
231−toListStable = sortOn fst . toList
232−
233161-- | Convert a value into 'Form'.
234162--
235163-- An example type and instance:
@@ -265,12 +193,12 @@ toListStable = sortOn fst . toList
265193-- instance 'ToForm' Person
266194-- @
267195--
268−-- The default implementation of 'toForm' is 'genericToForm'.
196+-- The default implementation will use 'toQueryParam' for each field's value.
269197class ToForm a where
270198 -- | Convert a value into 'Form'.
271199 toForm :: a -> Form
272− default toForm :: (Generic a, GToForm a (Rep a)) => a -> Form
273− toForm = genericToForm defaultFormOptions
200+ default toForm :: (Generic a, GToForm (Rep a)) => a -> Form
201+ toForm = genericToForm
274202
275203instance ToForm Form where toForm = id
276204
@@ -287,100 +215,34 @@ instance ToHttpApiData v => ToForm (IntMap [v]) where
287215 toForm = fromEntriesByKey . IntMap.toList
288216
289217-- | Convert a list of entries groupped by key into a 'Form'.
290−--
291−-- >>> fromEntriesByKey [("name",["Nick"]),("color",["red","blue"])]
292−-- fromList [("color","red"),("color","blue"),("name","Nick")]
293218fromEntriesByKey :: (ToFormKey k, ToHttpApiData v) => [(k, [v])] -> Form
294219fromEntriesByKey = Form . HashMap.fromListWith (<>) . map (toFormKey *** map toQueryParam)
295220
296−data Proxy3 a b c = Proxy3
297−
298−type family NotSupported (cls :: k1) (a :: k2) (reason :: Symbol) :: Constraint where
299−#if __GLASGOW_HASKELL__ < 800
300− -- this is just a placeholder case for older GHCs to not freak out on an empty closed type family
301− NotSupported cls a "this type family is actually empty" = ()
302−#else
303− NotSupported cls a reason = TypeError
304− ( 'Text "Cannot derive a Generic-based " ':<>: 'ShowType cls ':<>: 'Text " instance for " ':<>: 'ShowType a ':<>: 'Text "." ':$$:
305− 'ShowType a ':<>: 'Text " " ':<>: 'Text reason ':<>: 'Text "," ':$$:
306− 'Text "but Generic-based " ':<>: 'ShowType cls ':<>: 'Text " instances can be derived only for records" ':$$:
307− 'Text "(i.e. product types with named fields)." )
308−#endif
309−
310221-- | A 'Generic'-based implementation of 'toForm'.
311222-- This is used as a default implementation in 'ToForm'.
312−--
313−-- Note that this only works for records (i.e. product data types with named fields):
314−--
315−-- @
316−-- data Person = Person
317−-- { name :: String
318−-- , age :: Int
319−-- } deriving ('Generic')
320−-- @
321−--
322−-- In this implementation each field's value gets encoded using `toQueryParam`.
323−-- Two field types are exceptions:
324−--
325−-- - for values of type @'Maybe' a@ an entry is added to the 'Form' only when it is @'Just' x@
326−-- and the encoded value is @'toQueryParam' x@; 'Nothing' values are omitted from the 'Form';
327−--
328−-- - for values of type @[a]@ (except @['Char']@) an entry is added for every item in the list;
329−-- if the list is empty no entries are added to the 'Form';
330−--
331−-- Here's an example:
332−--
333−-- @
334−-- data Post = Post
335−-- { title :: String
336−-- , subtitle :: Maybe String
337−-- , comments :: [String]
338−-- } deriving ('Generic', 'Show')
339−--
340−-- instance 'ToForm' Post
341−-- @
342−--
343−-- >>> urlEncodeAsFormStable Post { title = "Test", subtitle = Nothing, comments = ["Nice post!", "+1"] }
344−-- "comments=Nice%20post%21&comments=%2B1&title=Test"
345−genericToForm :: forall a. (Generic a, GToForm a (Rep a)) => FormOptions -> a -> Form
346−genericToForm opts = gToForm (Proxy :: Proxy a) opts . from
223+genericToForm :: (Generic a, GToForm (Rep a)) => a -> Form
224+genericToForm = gToForm . from
347225
348−class GToForm t (f :: * -> *) where
349− gToForm :: Proxy t -> FormOptions -> f x -> Form
226+class GToForm (f :: * -> *) where
227+ gToForm :: f x -> Form
350228
351−instance (GToForm t f, GToForm t g) => GToForm t (f :*: g) where
352− gToForm p opts (a :*: b) = gToForm p opts a <> gToForm p opts b
229+instance (GToForm f, GToForm g) => GToForm (f :*: g) where
230+ gToForm (a :*: b) = gToForm a <> gToForm b
353231
354−instance (GToForm t f) => GToForm t (M1 D x f) where
355− gToForm p opts (M1 a) = gToForm p opts a
232+instance (GToForm f, GToForm g) => GToForm (f :+: g) where
233+ gToForm (L1 a) = gToForm a
234+ gToForm (R1 a) = gToForm a
356235
357−instance (GToForm t f) => GToForm t (M1 C x f) where
358− gToForm p opts (M1 a) = gToForm p opts a
236+instance (GToForm f) => GToForm (M1 D x f) where
237+ gToForm (M1 a) = gToForm a
359238
360−instance OVERLAPPABLE_ (Selector s, ToHttpApiData c) => GToForm t (M1 S s (K1 i c)) where
361− gToForm _ opts (M1 (K1 c)) = fromList [(key, toQueryParam c)]
362− where
363− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
364−
365−instance (Selector s, ToHttpApiData c) => GToForm t (M1 S s (K1 i (Maybe c))) where
366− gToForm _ opts (M1 (K1 c)) =
367− case c of
368− Nothing -> mempty
369− Just x -> fromList [(key, toQueryParam x)]
370− where
371− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
372−
373−instance (Selector s, ToHttpApiData c) => GToForm t (M1 S s (K1 i [c])) where
374− gToForm _ opts (M1 (K1 cs)) = fromList (map (\c -> (key, toQueryParam c)) cs)
375− where
376− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
239+instance (GToForm f) => GToForm (M1 C x f) where
240+ gToForm (M1 a) = gToForm a
377241
378−instance OVERLAPPING_ (Selector s) => GToForm t (M1 S s (K1 i String)) where
379− gToForm _ opts (M1 (K1 c)) = fromList [(key, toQueryParam c)]
242+instance (Selector s, ToHttpApiData c) => GToForm (M1 S s (K1 i c)) where
243+ gToForm (M1 (K1 c)) = fromList [(key, toQueryParam c)]
380244 where
381− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
382−
383−instance NotSupported ToForm t "is a sum type" => GToForm t (f :+: g) where gToForm = error "impossible"
245+ key = Text.pack $ selName (Proxy3 :: Proxy3 s g p)
384246
385247-- | Parse 'Form' into a value.
386248--
@@ -392,9 +254,9 @@ instance NotSupported ToForm t "is a sum type" => GToForm t (f :+: g) where gToF
392254-- , age :: Int }
393255--
394256-- instance 'FromForm' Person where
395−-- 'fromForm' f = Person
396−-- '<$>' 'parseUnique' "name" f
397−-- '<*>' 'parseUnique' "age" f
257+-- 'fromForm' (Form m) = Person
258+-- '<$>' 'parseUnique' "name" m
259+-- '<*>' 'parseUnique' "age" m
398260-- @
399261--
400262-- Instead of manually writing @'FromForm'@ instances you can
@@ -415,17 +277,16 @@ instance NotSupported ToForm t "is a sum type" => GToForm t (f :+: g) where gToF
415277-- instance 'FromForm' Person
416278-- @
417279--
418−-- The default implementation of 'fromForm' is 'genericFromForm'.
419−-- It only works for records and it will use 'parseQueryParam' for each field's value.
280+-- The default implementation will use 'parseQueryParam' for each field's value.
420281class FromForm a where
421282 -- | Parse 'Form' into a value.
422283 fromForm :: Form -> Either Text a
423− default fromForm :: (Generic a, GFromForm a (Rep a)) => Form -> Either Text a
424− fromForm = genericFromForm defaultFormOptions
284+ default fromForm :: (Generic a, GFromForm (Rep a))
285+ => Form -> Either Text a
286+ fromForm = genericFromForm
425287
426288instance FromForm Form where fromForm = pure
427289
428−-- | _NOTE:_ this conversion is unstable and may result in different key order (but not values).
429290instance (FromFormKey k, FromHttpApiData v) => FromForm [(k, v)] where
430291 fromForm = fmap (concatMap (\(k, vs) -> map ((,) k) vs)) . toEntriesByKey
431292
@@ -439,254 +300,157 @@ instance FromHttpApiData v => FromForm (IntMap [v]) where
439300 fromForm = fmap (IntMap.fromListWith (<>)) . toEntriesByKey
440301
441302-- | Parse a 'Form' into a list of entries groupped by key.
442−--
443−-- _NOTE:_ this conversion is unstable and may result in different key order
444−-- (but not values). For a stable encoding see 'toEntriesByKeyStable'.
445303toEntriesByKey :: (FromFormKey k, FromHttpApiData v) => Form -> Either Text [(k, [v])]
446304toEntriesByKey = traverse parseGroup . HashMap.toList . unForm
447305 where
448306 parseGroup (k, vs) = (,) <$> parseFormKey k <*> traverse parseQueryParam vs
449307
450−-- | Parse a 'Form' into a list of entries groupped by key.
451−--
452−-- >>> toEntriesByKeyStable [("name", "Nick"), ("color", "red"), ("color", "white")] :: Either Text [(Text, [Text])]
453−-- Right [("color",["red","white"]),("name",["Nick"])]
454−--
455−-- For an unstable (but faster) conversion see 'toEntriesByKey'.
456−toEntriesByKeyStable :: (Ord k, FromFormKey k, FromHttpApiData v) => Form -> Either Text [(k, [v])]
457−toEntriesByKeyStable = fmap (sortOn fst) . toEntriesByKey
458−
459308-- | A 'Generic'-based implementation of 'fromForm'.
460309-- This is used as a default implementation in 'FromForm'.
461−--
462−-- Note that this only works for records (i.e. product data types with named fields):
463−--
464−-- @
465−-- data Person = Person
466−-- { name :: String
467−-- , age :: Int
468−-- } deriving ('Generic')
469−-- @
470−--
471−-- In this implementation each field's value gets decoded using `parseQueryParam`.
472−-- Two field types are exceptions:
473−--
474−-- - for values of type @'Maybe' a@ an entry is parsed if present in the 'Form'
475−-- and the is decoded with 'parseQueryParam'; if no entry is present result is 'Nothing';
476−--
477−-- - for values of type @[a]@ (except @['Char']@) all entries are parsed to produce a list of parsed values;
478−--
479−-- Here's an example:
480−--
481−-- @
482−-- data Post = Post
483−-- { title :: String
484−-- , subtitle :: Maybe String
485−-- , comments :: [String]
486−-- } deriving ('Generic', 'Show')
487−--
488−-- instance 'FromForm' Post
489−-- @
490−--
491−-- >>> urlDecodeAsForm "comments=Nice%20post%21&comments=%2B1&title=Test" :: Either Text Post
492−-- Right (Post {title = "Test", subtitle = Nothing, comments = ["Nice post!","+1"]})
493−genericFromForm :: forall a. (Generic a, GFromForm a (Rep a)) => FormOptions -> Form -> Either Text a
494−genericFromForm opts f = to <$> gFromForm (Proxy :: Proxy a) opts f
495−
496−class GFromForm t (f :: * -> *) where
497− gFromForm :: Proxy t -> FormOptions -> Form -> Either Text (f x)
498−
499−instance (GFromForm t f, GFromForm t g) => GFromForm t (f :*: g) where
500− gFromForm p opts f = (:*:) <$> gFromForm p opts f <*> gFromForm p opts f
310+genericFromForm :: (Generic a, GFromForm (Rep a))
311+ => Form -> Either Text a
312+genericFromForm f = to <$> gFromForm f
501313
502−instance GFromForm t f => GFromForm t (M1 D x f) where
503− gFromForm p opts f = M1 <$> gFromForm p opts f
314+class GFromForm (f :: * -> *) where
315+ gFromForm :: Form -> Either Text (f x)
504316
505−instance GFromForm t f => GFromForm t (M1 C x f) where
506− gFromForm p opts f = M1 <$> gFromForm p opts f
317+instance (GFromForm f, GFromForm g) => GFromForm (f :*: g) where
318+ gFromForm f = (:*:) <$> gFromForm f <*> gFromForm f
507319
508−instance OVERLAPPABLE_ (Selector s, FromHttpApiData c) => GFromForm t (M1 S s (K1 i c)) where
509− gFromForm _ opts form = M1 . K1 <$> parseUnique key form
320+instance (GFromForm f, GFromForm g) => GFromForm (f :+: g) where
321+ gFromForm f
322+ = fmap L1 (gFromForm f)
323+ <!> fmap R1 (gFromForm f)
510324 where
511− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
325+ Left _ <!> y = y
326+ x <!> _ = x
512327
513−instance (Selector s, FromHttpApiData c) => GFromForm t (M1 S s (K1 i (Maybe c))) where
514− gFromForm _ opts form = M1 . K1 <$> parseMaybe key form
328+instance (Selector s, FromHttpApiData f) => GFromForm (M1 S s (K1 i f)) where
329+ gFromForm form = M1 . K1 <$> parseUnique key form
515330 where
516− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
331+ key = Text.pack $ selName (Proxy3 :: Proxy3 s g p)
517332
518−instance (Selector s, FromHttpApiData c) => GFromForm t (M1 S s (K1 i [c])) where
519− gFromForm _ opts form = M1 . K1 <$> parseAll key form
520− where
521− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
522−
523−instance OVERLAPPING_ (Selector s) => GFromForm t (M1 S s (K1 i String)) where
524− gFromForm _ opts form = M1 . K1 <$> parseUnique key form
525− where
526− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
333+instance (GFromForm f) => GFromForm (M1 D x f) where
334+ gFromForm f = M1 <$> gFromForm f
527335
528−instance NotSupported FromForm t "is a sum type" => GFromForm t (f :+: g) where gFromForm = error "impossible"
336+instance (GFromForm f) => GFromForm (M1 C x f) where
337+ gFromForm f = M1 <$> gFromForm f
529338
530339-- | Encode a 'Form' to an @application/x-www-form-urlencoded@ 'BSL.ByteString'.
531340--
532−-- _NOTE:_ this encoding is unstable and may result in different key order
533−-- (but not values). For a stable encoding see 'urlEncodeFormStable'.
534−urlEncodeForm :: Form -> BSL.ByteString
535−urlEncodeForm = urlEncodeParams . toList
536−
537−-- | Encode a 'Form' to an @application/x-www-form-urlencoded@ 'BSL.ByteString'.
538−--
539−-- For an unstable (but faster) encoding see 'urlEncodeForm'.
540−--
541341-- Key-value pairs get encoded to @key=value@ and separated by @&@:
542342--
543−-- >>> urlEncodeFormStable [("name", "Julian"), ("lastname", "Arni")]
343+-- >>> encodeForm [("name", "Julian"), ("lastname", "Arni")]
544344-- "lastname=Arni&name=Julian"
545345--
546346-- Keys with empty values get encoded to just @key@ (without the @=@ sign):
547347--
548−-- >>> urlEncodeFormStable [("is_test", "")]
348+-- >>> encodeForm [("is_test", "")]
549349-- "is_test"
550350--
551351-- Empty keys are allowed too:
552352--
553−-- >>> urlEncodeFormStable [("", "foobar")]
353+-- >>> encodeForm [("", "foobar")]
554354-- "=foobar"
555355--
556−-- However, if both key and value are empty, the key-value pair is ignored.
557−-- (This prevents @'urlDecodeForm' . 'urlEncodeFormStable'@ from being a true isomorphism).
356+-- However, if not key and value are empty, the key-value pair is ignored.
357+-- (This prevents @'decodeForm' . 'encodeForm'@ from being a true isomorphism).
558358--
559−-- >>> urlEncodeFormStable [("", "")]
359+-- >>> encodeForm [("", "")]
560360-- ""
561361--
562362-- Everything is escaped with @'escapeURIString' 'isUnreserved'@:
563363--
564−-- >>> urlEncodeFormStable [("fullname", "Andres Löh")]
364+-- >>> encodeForm [("fullname", "Andres Löh")]
565365-- "fullname=Andres%20L%C3%B6h"
566−urlEncodeFormStable :: Form -> BSL.ByteString
567−urlEncodeFormStable = urlEncodeParams . sortOn fst . toList
568−
569−-- | Encode a list of key-value pairs to an @application/x-www-form-urlencoded@ 'BSL.ByteString'.
570−--
571−-- See also 'urlEncodeFormStable'.
572−urlEncodeParams :: [(Text, Text)] -> BSL.ByteString
573−urlEncodeParams = toLazyByteString . mconcat . intersperse (shortByteString "&") . map encodePair
366+encodeForm :: Form -> BSL.ByteString
367+encodeForm xs = BSL.intercalate "&" $ map (BSL.fromStrict . encodePair) $ toList xs
574368 where
575− escape = urlEncodeBuilder True . Text.encodeUtf8
369+ escape = Text.encodeUtf8 . Text.pack . escapeURIString isUnreserved . Text.unpack
576370
577371 encodePair (k, "") = escape k
578− encodePair (k, v) = escape k <> shortByteString "=" <> escape v
372+ encodePair (k, v) = escape k <> "=" <> escape v
373+
579374
580375-- | Decode an @application/x-www-form-urlencoded@ 'BSL.ByteString' to a 'Form'.
581376--
582377-- Key-value pairs get decoded normally:
583378--
584−-- >>> urlDecodeForm "name=Greg&lastname=Weber"
379+-- >>> decodeForm "name=Greg&lastname=Weber"
585380-- Right (fromList [("lastname","Weber"),("name","Greg")])
586381--
587382-- Keys with no values get decoded to pairs with empty values.
588383--
589−-- >>> urlDecodeForm "is_test"
384+-- >>> decodeForm "is_test"
590385-- Right (fromList [("is_test","")])
591386--
592387-- Empty keys are allowed:
593388--
594−-- >>> urlDecodeForm "=foobar"
389+-- >>> decodeForm "=foobar"
595390-- Right (fromList [("","foobar")])
596391--
597392-- The empty string gets decoded into an empty 'Form':
598393--
599−-- >>> urlDecodeForm ""
394+-- >>> decodeForm ""
600395-- Right (fromList [])
601396--
602397-- Everything is un-escaped with 'unEscapeString':
603398--
604−-- >>> urlDecodeForm "fullname=Andres%20L%C3%B6h"
399+-- >>> decodeForm "fullname=Andres%20L%C3%B6h"
605400-- Right (fromList [("fullname","Andres L\246h")])
606401--
607402-- Improperly formed strings result in an error:
608403--
609−-- >>> urlDecodeForm "this=has=too=many=equals"
404+-- >>> decodeForm "this=has=too=many=equals"
610405-- Left "not a valid pair: this=has=too=many=equals"
611−urlDecodeForm :: BSL.ByteString -> Either Text Form
612−urlDecodeForm = fmap toForm . urlDecodeParams
613−
614−-- | Decode an @application/x-www-form-urlencoded@ 'BSL.ByteString' to a list of key-value pairs.
615−--
616−-- See also 'urlDecodeForm'.
617−urlDecodeParams :: BSL.ByteString -> Either Text [(Text, Text)]
618−urlDecodeParams bs = traverse parsePair pairs
406+decodeForm :: BSL.ByteString -> Either Text Form
407+decodeForm bs = toForm <$> traverse parsePair pairs
619408 where
620− pairs = map (BSL8.split '=') (BSL8.split '&' bs)
409+ pairs = map (Text.decodeUtf8With lenientDecode . BSL.toStrict) (BSL8.split '&' bs)
621410
622− unescape = Text.decodeUtf8With lenientDecode . urlDecode True . BSL.toStrict
411+ unescape = Text.pack . unEscapeString . Text.unpack . Text.replace "+" "%20"
623412
413+ parsePair :: Text -> Either Text (Text, Text)
624414 parsePair p =
625− case map unescape p of
626− [k, v] -> return (k, v)
627− [k] -> return (k, "")
628− xs -> Left $ "not a valid pair: " <> Text.intercalate "=" xs
415+ case Text.splitOn "=" p of
416+ [k, v] -> return (unescape k, unescape v)
417+ [k] -> return (unescape k, "" )
418+ _ -> Left $ "not a valid pair: " <> p
629419
420+data Proxy3 a b c = Proxy3
630421
631422-- | This is a convenience function for decoding a
632423-- @application/x-www-form-urlencoded@ 'BSL.ByteString' directly to a datatype
633424-- that has an instance of 'FromForm'.
634425--
635−-- This is effectively @'fromForm' '<=<' 'urlDecodeForm'@.
426+-- This is effectively @'fromForm' '<=<' 'decodeForm'@.
636427--
637−-- >>> urlDecodeAsForm "name=Dennis&age=22" :: Either Text Person
428+-- >>> decodeAsForm "name=Dennis&age=22" :: Either Text Person
638429-- Right (Person {name = "Dennis", age = 22})
639−urlDecodeAsForm :: FromForm a => BSL.ByteString -> Either Text a
640−urlDecodeAsForm = fromForm <=< urlDecodeForm
430+decodeAsForm :: FromForm a => BSL.ByteString -> Either Text a
431+decodeAsForm = fromForm <=< decodeForm
641432
642433-- | This is a convenience function for encoding a datatype that has instance
643434-- of 'ToForm' directly to a @application/x-www-form-urlencoded@
644435-- 'BSL.ByteString'.
645436--
646−-- This is effectively @'urlEncodeForm' . 'toForm'@.
437+-- This is effectively @'encodeForm' . 'toForm'@.
647438--
648−-- _NOTE:_ this encoding is unstable and may result in different key order
649−-- (but not values). For a stable encoding see 'urlEncodeAsFormStable'.
650−urlEncodeAsForm :: ToForm a => a -> BSL.ByteString
651−urlEncodeAsForm = urlEncodeForm . toForm
652−
653−-- | This is a convenience function for encoding a datatype that has instance
654−-- of 'ToForm' directly to a @application/x-www-form-urlencoded@
655−-- 'BSL.ByteString'.
656−--
657−-- This is effectively @'urlEncodeFormStable' . 'toForm'@.
658−--
659−-- >>> urlEncodeAsFormStable Person {name = "Dennis", age = 22}
439+-- >>> encodeAsForm Person {name = "Dennis", age = 22}
660440-- "age=22&name=Dennis"
661−urlEncodeAsFormStable :: ToForm a => a -> BSL.ByteString
662−urlEncodeAsFormStable = urlEncodeFormStable . toForm
441+encodeAsForm :: ToForm a => a -> BSL.ByteString
442+encodeAsForm = encodeForm . toForm
663443
664444-- | Find all values corresponding to a given key in a 'Form'.
665445--
666−-- >>> lookupAll "name" []
446+-- >>> lookupKey "name" []
667447-- []
668−-- >>> lookupAll "name" [("name", "Oleg")]
448+-- >>> lookupKey "name" [("name", "Oleg")]
669449-- ["Oleg"]
670−-- >>> lookupAll "name" [("name", "Oleg"), ("name", "David")]
450+-- >>> lookupKey "name" [("name", "Oleg"), ("name", "David")]
671451-- ["Oleg","David"]
672−lookupAll :: Text -> Form -> [Text]
673−lookupAll key = F.concat . HashMap.lookup key . unForm
674−
675−-- | Lookup an optional value for a key.
676−-- Fail if there is more than one value.
677−--
678−-- >>> lookupMaybe "name" []
679−-- Right Nothing
680−-- >>> lookupMaybe "name" [("name", "Oleg")]
681−-- Right (Just "Oleg")
682−-- >>> lookupMaybe "name" [("name", "Oleg"), ("name", "David")]
683−-- Left "Duplicate key \"name\""
684−lookupMaybe :: Text -> Form -> Either Text (Maybe Text)
685−lookupMaybe key form =
686− case lookupAll key form of
687− [] -> pure Nothing
688− [v] -> pure (Just v)
689− _ -> Left $ "Duplicate key " <> Text.pack (show key)
452+lookupKey :: Text -> Form -> [Text]
453+lookupKey key = concat . HashMap.lookup key . unForm
690454
691455-- | Lookup a unique value for a key.
692456-- Fail if there is zero or more than one value.
@@ -698,43 +462,13 @@ lookupMaybe key form =
698462-- >>> lookupUnique "name" [("name", "Oleg"), ("name", "David")]
699463-- Left "Duplicate key \"name\""
700464lookupUnique :: Text -> Form -> Either Text Text
701−lookupUnique key form = do
702− mv <- lookupMaybe key form
703− case mv of
704− Just v -> pure v
705− Nothing -> Left $ "Could not find key " <> Text.pack (show key)
706−
707−-- | Lookup all values for a given key in a 'Form' and parse them with 'parseQueryParams'.
708−--
709−-- >>> parseAll "age" [] :: Either Text [Word8]
710−-- Right []
711−-- >>> parseAll "age" [("age", "8"), ("age", "seven")] :: Either Text [Word8]
712−-- Left "could not parse: `seven' (input does not start with a digit)"
713−-- >>> parseAll "age" [("age", "8"), ("age", "777")] :: Either Text [Word8]
714−-- Left "out of bounds: `777' (should be between 0 and 255)"
715−-- >>> parseAll "age" [("age", "12"), ("age", "25")] :: Either Text [Word8]
716−-- Right [12,25]
717−parseAll :: FromHttpApiData v => Text -> Form -> Either Text [v]
718−parseAll key = parseQueryParams . lookupAll key
719−
720−-- | Lookup an optional value for a given key and parse it with 'parseQueryParam'.
721−-- Fail if there is more than one value for the key.
722−--
723−-- >>> parseMaybe "age" [] :: Either Text (Maybe Word8)
724−-- Right Nothing
725−-- >>> parseMaybe "age" [("age", "12"), ("age", "25")] :: Either Text (Maybe Word8)
726−-- Left "Duplicate key \"age\""
727−-- >>> parseMaybe "age" [("age", "seven")] :: Either Text (Maybe Word8)
728−-- Left "could not parse: `seven' (input does not start with a digit)"
729−-- >>> parseMaybe "age" [("age", "777")] :: Either Text (Maybe Word8)
730−-- Left "out of bounds: `777' (should be between 0 and 255)"
731−-- >>> parseMaybe "age" [("age", "7")] :: Either Text (Maybe Word8)
732−-- Right (Just 7)
733−parseMaybe :: FromHttpApiData v => Text -> Form -> Either Text (Maybe v)
734−parseMaybe key = parseQueryParams <=< lookupMaybe key
465+lookupUnique key form =
466+ case lookupKey key form of
467+ [v] -> pure v
468+ [] -> Left $ "Could not find key " <> Text.pack (show key)
469+ _ -> Left $ "Duplicate key " <> Text.pack (show key)
735470
736471-- | Lookup a unique value for a given key and parse it with 'parseQueryParam'.
737−-- Fail if there is zero or more than one value for the key.
738472--
739473-- >>> parseUnique "age" [] :: Either Text Word8
740474-- Left "Could not find key \"age\""
@@ -749,48 +483,16 @@ parseMaybe key = parseQueryParams <=< lookupMaybe key
749483parseUnique :: FromHttpApiData v => Text -> Form -> Either Text v
750484parseUnique key form = lookupUnique key form >>= parseQueryParam
751485
752−-- | 'Generic'-based deriving options for 'ToForm' and 'FromForm'.
753−--
754−-- A common use case for non-default 'FormOptions'
755−-- is to strip a prefix off of field labels:
756−--
757−-- @
758−-- data Project = Project
759−-- { projectName :: String
760−-- , projectSize :: Int
761−-- } deriving ('Generic', 'Show')
762−--
763−-- myOptions :: 'FormOptions'
764−-- myOptions = 'FormOptions'
765−-- { 'fieldLabelModifier' = 'map' 'toLower' . 'drop' ('length' \"project\") }
766−--
767−-- instance 'ToForm' Project where
768−-- 'toForm' = 'genericToForm' myOptions
769−--
770−-- instance 'FromForm' Project where
771−-- 'fromForm' = 'genericFromForm' myOptions
772−-- @
773−--
774−-- >>> urlEncodeAsFormStable Project { projectName = "http-api-data", projectSize = 172 }
775−-- "name=http-api-data&size=172"
776−-- >>> urlDecodeAsForm "name=http-api-data&size=172" :: Either Text Project
777−-- Right (Project {projectName = "http-api-data", projectSize = 172})
778−data FormOptions = FormOptions
779− { -- | Function applied to field labels. Handy for removing common record prefixes for example.
780− fieldLabelModifier :: String -> String
781− }
782−
783−-- | Default encoding 'FormOptions'.
486+-- | Lookup all values for a given key in a 'Form' and parse them with 'parseQueryParams'.
784487--
785−-- @
786−-- 'FormOptions'
787−-- { 'fieldLabelModifier' = id
788−-- }
789−-- @
790−defaultFormOptions :: FormOptions
791−defaultFormOptions = FormOptions
792− { fieldLabelModifier = id
793− }
488+-- >>> parseAll "age" [] :: Either Text [Word8]
489+-- Right []
490+-- >>> parseAll "age" [("age", "8"), ("age", "seven")] :: Either Text [Word8]
491+-- Left "could not parse: `seven' (input does not start with a digit)"
492+-- >>> parseAll "age" [("age", "8"), ("age", "777")] :: Either Text [Word8]
493+-- Left "out of bounds: `777' (should be between 0 and 255)"
494+-- >>> parseAll "age" [("age", "12"), ("age", "25")] :: Either Text [Word8]
495+-- Right [12,25]
496+parseAll :: FromHttpApiData v => Text -> Form -> Either Text [v]
497+parseAll key = parseQueryParams . lookupKey key
794498
795−sortOn :: Ord b => (a -> b) -> [a] -> [a]
796−sortOn f = sortBy (comparing f)