]> git.immae.eu Git - github/fretlink/purs-loader.git/blob - src/PursLoader/Loader.purs
Updating example
[github/fretlink/purs-loader.git] / src / PursLoader / Loader.purs
1 module PursLoader.Loader
2 ( Effects()
3 , loader
4 , loaderFn
5 ) where
6
7 import Prelude (Unit(), ($), (>>=), (<$>), (<*>), (<<<), (++), bind, const)
8
9 import Control.Bind (join)
10 import Control.Monad.Eff (Eff())
11 import Control.Monad.Eff.Exception (Error(), error)
12
13 import Data.Array ((!!))
14 import Data.Function (Fn2(), mkFn2)
15 import Data.Maybe (Maybe(..), maybe)
16 import Data.Either (either)
17 import Data.Foreign (Foreign())
18 import Data.Foreign.Class (read)
19 import Data.Foreign.Null (runNull)
20 import Data.String.Regex (Regex(), match, noFlags, regex)
21
22 import Unsafe.Coerce (unsafeCoerce)
23
24 import PursLoader.LoaderRef
25 ( LoaderRef()
26 , Loader()
27 , async
28 , cacheable
29 , query
30 , clearDependencies
31 , addDependency
32 , resourcePath
33 )
34
35 import PursLoader.LoaderUtil (parseQuery)
36 import PursLoader.Options (runOptions)
37 import PursLoader.Path (dirname, relative)
38
39 type Effects eff = (loader :: Loader | eff)
40
41 type PurescriptWebpackPluginContext eff = { compile :: (Foreign -> Eff (Effects eff) Unit) -> Eff (Effects eff) Unit }
42
43 loader :: forall eff. LoaderRef -> String -> Eff (Effects eff) Unit
44 loader ref source = do
45 callback <- async ref
46
47 cacheable ref
48
49 let parsed = parseQuery $ query ref
50
51 options = either (const Nothing) (Just <<< runOptions) (read parsed)
52
53 moduleName = join $ match moduleRegex source >>= \as -> as !! 1
54
55 resourceDir = dirname (resourcePath ref)
56
57 modulePath = (\opts -> relative resourceDir opts.pscBundle) <$> options
58
59 result = (\path name -> "module.exports = require('" ++ path ++ "')['" ++ name ++ "'];") <$> modulePath <*> moduleName
60
61 clearDependencies ref
62
63 addDependency ref (resourcePath ref)
64
65 pluginContext.compile (\err -> maybe (callback (Just $ error "Failed to run loader") "")
66 (callback (compileError err)) result)
67 where
68 moduleRegex :: Regex
69 moduleRegex = regex "(?:^|\\n)module\\s+([\\w\\.]+)" noFlags { ignoreCase = true }
70
71 pluginContext :: PurescriptWebpackPluginContext eff
72 pluginContext = (unsafeCoerce ref).purescriptWebpackPluginContext
73
74 compileError :: Foreign -> Maybe Error
75 compileError value = either (const $ Just (error "Failed to compile")) ((<$>) error) (runNull <$> read value)
76
77 loaderFn :: forall eff. Fn2 LoaderRef String (Eff (Effects eff) Unit)
78 loaderFn = mkFn2 loader