module Test.WebDriver.Commands.Internal
( clientScripts ) where
import Control.Applicative
import Data.Maybe (catMaybes)
import Data.Monoid ((<>))
import Language.JavaScript.Parser (JSNode(..), Node(..))
import qualified Data.HashMap.Lazy as M
import qualified Data.Text as T
import qualified Language.JavaScript.Parser as JS
parseClientTop :: JSNode -> [(T.Text,T.Text)]
parseClientTop (NN (JSSourceElementsTop es)) = catMaybes $ map parseClientDef es
parseClientTop _ = []
buildFunction :: Node -> T.Text
buildFunction func = "return (" <> T.pack func' <> ").apply(null, arguments);"
where
func' = dropWhile (=='\n') $ JS.renderToString $ NN func
parseClientDef :: JSNode -> Maybe (T.Text, T.Text)
parseClientDef (NN (JSExpression
[NN (JSMemberDot
[NT (JSIdentifier "clientSideScripts") _ _]
_
(NT (JSIdentifier name) _ _))
, NN (JSOperator (NT (JSLiteral "=") _ _))
, NN (func@(JSFunctionExpression _ _ _ _ _ _))
]))
= Just (T.pack name, buildFunction func)
parseClientDef _ = Nothing
clientScripts :: String -> Either String (M.HashMap T.Text T.Text)
clientScripts j = M.fromList . parseClientTop <$> JS.parse j "<client>"