Bug:Fix file validation issue
[vnfsdk/refrepo.git] / vnfmarket / src / main / webapp / vnfmarket / node_modules / karma / lib / middleware / karma.js
1 /**
2  * Karma middleware is responsible for serving:
3  * - client.html (the entrypoint for capturing a browser)
4  * - debug.html
5  * - context.html (the execution context, loaded within an iframe)
6  * - karma.js
7  *
8  * The main part is generating context.html, as it contains:
9  * - generating mappings
10  * - including <script> and <link> tags
11  * - setting propert caching headers
12  */
13
14 var path = require('path')
15 var util = require('util')
16 var url = require('url')
17
18 var urlparse = function (urlStr) {
19   var urlObj = url.parse(urlStr, true)
20   urlObj.query = urlObj.query || {}
21   return urlObj
22 }
23
24 var common = require('./common')
25
26 var VERSION = require('../constants').VERSION
27 var SCRIPT_TAG = '<script type="%s" src="%s"></script>'
28 var LINK_TAG_CSS = '<link type="text/css" href="%s" rel="stylesheet">'
29 var LINK_TAG_HTML = '<link href="%s" rel="import">'
30 var SCRIPT_TYPE = {
31   '.js': 'text/javascript',
32   '.dart': 'application/dart'
33 }
34
35 var filePathToUrlPath = function (filePath, basePath) {
36   if (filePath.indexOf(basePath) === 0) {
37     return '/base' + filePath.substr(basePath.length)
38   }
39
40   return '/absolute' + filePath
41 }
42
43 var getXUACompatibleMetaElement = function (url) {
44   var tag = ''
45   var urlObj = urlparse(url)
46   if (urlObj.query['x-ua-compatible']) {
47     tag = '\n<meta http-equiv="X-UA-Compatible" content="' +
48       urlObj.query['x-ua-compatible'] + '"/>'
49   }
50   return tag
51 }
52
53 var getXUACompatibleUrl = function (url) {
54   var value = ''
55   var urlObj = urlparse(url)
56   if (urlObj.query['x-ua-compatible']) {
57     value = '?x-ua-compatible=' + encodeURIComponent(urlObj.query['x-ua-compatible'])
58   }
59   return value
60 }
61
62 var createKarmaMiddleware = function (filesPromise, serveStaticFile,
63   /* config.basePath */ basePath, /* config.urlRoot */ urlRoot, /* config.client */ client) {
64   return function (request, response, next) {
65     var requestUrl = request.normalizedUrl.replace(/\?.*/, '')
66
67     // redirect /__karma__ to /__karma__ (trailing slash)
68     if (requestUrl === urlRoot.substr(0, urlRoot.length - 1)) {
69       response.setHeader('Location', urlRoot)
70       response.writeHead(301)
71       return response.end('MOVED PERMANENTLY')
72     }
73
74     // ignore urls outside urlRoot
75     if (requestUrl.indexOf(urlRoot) !== 0) {
76       return next()
77     }
78
79     // remove urlRoot prefix
80     requestUrl = requestUrl.substr(urlRoot.length - 1)
81
82     // serve client.html
83     if (requestUrl === '/') {
84       return serveStaticFile('/client.html', response, function (data) {
85         return data
86           .replace('\n%X_UA_COMPATIBLE%', getXUACompatibleMetaElement(request.url))
87           .replace('%X_UA_COMPATIBLE_URL%', getXUACompatibleUrl(request.url))
88       })
89     }
90
91     // serve karma.js
92     if (requestUrl === '/karma.js') {
93       return serveStaticFile(requestUrl, response, function (data) {
94         return data.replace('%KARMA_URL_ROOT%', urlRoot)
95           .replace('%KARMA_VERSION%', VERSION)
96       })
97     }
98
99     // serve the favicon
100     if (requestUrl === '/favicon.ico') {
101       return serveStaticFile(requestUrl, response)
102     }
103
104     // serve context.html - execution context within the iframe
105     // or debug.html - execution context without channel to the server
106     if (requestUrl === '/context.html' || requestUrl === '/debug.html') {
107       return filesPromise.then(function (files) {
108         serveStaticFile(requestUrl, response, function (data) {
109           common.setNoCacheHeaders(response)
110
111           var scriptTags = files.included.map(function (file) {
112             var filePath = file.path
113             var fileExt = path.extname(filePath)
114
115             if (!file.isUrl) {
116               // TODO(vojta): serve these files from within urlRoot as well
117               filePath = filePathToUrlPath(filePath, basePath)
118
119               if (requestUrl === '/context.html') {
120                 filePath += '?' + file.sha
121               }
122             }
123
124             if (fileExt === '.css') {
125               return util.format(LINK_TAG_CSS, filePath)
126             }
127
128             if (fileExt === '.html') {
129               return util.format(LINK_TAG_HTML, filePath)
130             }
131
132             return util.format(SCRIPT_TAG, SCRIPT_TYPE[fileExt] || 'text/javascript', filePath)
133           })
134
135           // TODO(vojta): don't compute if it's not in the template
136           var mappings = files.served.map(function (file) {
137             // Windows paths contain backslashes and generate bad IDs if not escaped
138             var filePath = filePathToUrlPath(file.path, basePath).replace(/\\/g, '\\\\')
139
140             return util.format("  '%s': '%s'", filePath, file.sha)
141           })
142
143           var clientConfig = ''
144
145           if (requestUrl === '/debug.html') {
146             clientConfig = 'window.__karma__.config = ' + JSON.stringify(client) + ';\n'
147           }
148
149           mappings = 'window.__karma__.files = {\n' + mappings.join(',\n') + '\n};\n'
150
151           return data
152             .replace('%SCRIPTS%', scriptTags.join('\n'))
153             .replace('%CLIENT_CONFIG%', clientConfig)
154             .replace('%MAPPINGS%', mappings)
155             .replace('\n%X_UA_COMPATIBLE%', getXUACompatibleMetaElement(request.url))
156         })
157       }, function (errorFiles) {
158         serveStaticFile(requestUrl, response, function (data) {
159           common.setNoCacheHeaders(response)
160           return data.replace('%SCRIPTS%', '').replace('%CLIENT_CONFIG%', '').replace('%MAPPINGS%',
161             'window.__karma__.error("TEST RUN WAS CANCELLED because ' +
162             (errorFiles.length > 1 ? 'these files contain' : 'this file contains') +
163             ' some errors:\\n  ' + errorFiles.join('\\n  ') + '");')
164         })
165       })
166     }
167
168     return next()
169   }
170 }
171
172 createKarmaMiddleware.$inject = ['filesPromise', 'serveStaticFile',
173   'config.basePath', 'config.urlRoot', 'config.client']
174
175 // PUBLIC API
176 exports.create = createKarmaMiddleware