summaryrefslogtreecommitdiffstats
path: root/vnfmarket/src/main/webapp/vnfmarket/node_modules/karma/lib/middleware/karma.js
blob: a9186fa6538e1b59dbccdaa518fd6a6d2de03cd1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/**
 * Karma middleware is responsible for serving:
 * - client.html (the entrypoint for capturing a browser)
 * - debug.html
 * - context.html (the execution context, loaded within an iframe)
 * - karma.js
 *
 * The main part is generating context.html, as it contains:
 * - generating mappings
 * - including <script> and <link> tags
 * - setting propert caching headers
 */

var path = require('path')
var util = require('util')
var url = require('url')

var urlparse = function (urlStr) {
  var urlObj = url.parse(urlStr, true)
  urlObj.query = urlObj.query || {}
  return urlObj
}

var common = require('./common')

var VERSION = require('../constants').VERSION
var SCRIPT_TAG = '<script type="%s" src="%s"></script>'
var LINK_TAG_CSS = '<link type="text/css" href="%s" rel="stylesheet">'
var LINK_TAG_HTML = '<link href="%s" rel="import">'
var SCRIPT_TYPE = {
  '.js': 'text/javascript',
  '.dart': 'application/dart'
}

var filePathToUrlPath = function (filePath, basePath) {
  if (filePath.indexOf(basePath) === 0) {
    return '/base' + filePath.substr(basePath.length)
  }

  return '/absolute' + filePath
}

var getXUACompatibleMetaElement = function (url) {
  var tag = ''
  var urlObj = urlparse(url)
  if (urlObj.query['x-ua-compatible']) {
    tag = '\n<meta http-equiv="X-UA-Compatible" content="' +
      urlObj.query['x-ua-compatible'] + '"/>'
  }
  return tag
}

var getXUACompatibleUrl = function (url) {
  var value = ''
  var urlObj = urlparse(url)
  if (urlObj.query['x-ua-compatible']) {
    value = '?x-ua-compatible=' + encodeURIComponent(urlObj.query['x-ua-compatible'])
  }
  return value
}

var createKarmaMiddleware = function (filesPromise, serveStaticFile,
  /* config.basePath */ basePath, /* config.urlRoot */ urlRoot, /* config.client */ client) {
  return function (request, response, next) {
    var requestUrl = request.normalizedUrl.replace(/\?.*/, '')

    // redirect /__karma__ to /__karma__ (trailing slash)
    if (requestUrl === urlRoot.substr(0, urlRoot.length - 1)) {
      response.setHeader('Location', urlRoot)
      response.writeHead(301)
      return response.end('MOVED PERMANENTLY')
    }

    // ignore urls outside urlRoot
    if (requestUrl.indexOf(urlRoot) !== 0) {
      return next()
    }

    // remove urlRoot prefix
    requestUrl = requestUrl.substr(urlRoot.length - 1)

    // serve client.html
    if (requestUrl === '/') {
      return serveStaticFile('/client.html', response, function (data) {
        return data
          .replace('\n%X_UA_COMPATIBLE%', getXUACompatibleMetaElement(request.url))
          .replace('%X_UA_COMPATIBLE_URL%', getXUACompatibleUrl(request.url))
      })
    }

    // serve karma.js
    if (requestUrl === '/karma.js') {
      return serveStaticFile(requestUrl, response, function (data) {
        return data.replace('%KARMA_URL_ROOT%', urlRoot)
          .replace('%KARMA_VERSION%', VERSION)
      })
    }

    // serve the favicon
    if (requestUrl === '/favicon.ico') {
      return serveStaticFile(requestUrl, response)
    }

    // serve context.html - execution context within the iframe
    // or debug.html - execution context without channel to the server
    if (requestUrl === '/context.html' || requestUrl === '/debug.html') {
      return filesPromise.then(function (files) {
        serveStaticFile(requestUrl, response, function (data) {
          common.setNoCacheHeaders(response)

          var scriptTags = files.included.map(function (file) {
            var filePath = file.path
            var fileExt = path.extname(filePath)

            if (!file.isUrl) {
              // TODO(vojta): serve these files from within urlRoot as well
              filePath = filePathToUrlPath(filePath, basePath)

              if (requestUrl === '/context.html') {
                filePath += '?' + file.sha
              }
            }

            if (fileExt === '.css') {
              return util.format(LINK_TAG_CSS, filePath)
            }

            if (fileExt === '.html') {
              return util.format(LINK_TAG_HTML, filePath)
            }

            return util.format(SCRIPT_TAG, SCRIPT_TYPE[fileExt] || 'text/javascript', filePath)
          })

          // TODO(vojta): don't compute if it's not in the template
          var mappings = files.served.map(function (file) {
            // Windows paths contain backslashes and generate bad IDs if not escaped
            var filePath = filePathToUrlPath(file.path, basePath).replace(/\\/g, '\\\\')

            return util.format("  '%s': '%s'", filePath, file.sha)
          })

          var clientConfig = ''

          if (requestUrl === '/debug.html') {
            clientConfig = 'window.__karma__.config = ' + JSON.stringify(client) + ';\n'
          }

          mappings = 'window.__karma__.files = {\n' + mappings.join(',\n') + '\n};\n'

          return data
            .replace('%SCRIPTS%', scriptTags.join('\n'))
            .replace('%CLIENT_CONFIG%', clientConfig)
            .replace('%MAPPINGS%', mappings)
            .replace('\n%X_UA_COMPATIBLE%', getXUACompatibleMetaElement(request.url))
        })
      }, function (errorFiles) {
        serveStaticFile(requestUrl, response, function (data) {
          common.setNoCacheHeaders(response)
          return data.replace('%SCRIPTS%', '').replace('%CLIENT_CONFIG%', '').replace('%MAPPINGS%',
            'window.__karma__.error("TEST RUN WAS CANCELLED because ' +
            (errorFiles.length > 1 ? 'these files contain' : 'this file contains') +
            ' some errors:\\n  ' + errorFiles.join('\\n  ') + '");')
        })
      })
    }

    return next()
  }
}

createKarmaMiddleware.$inject = ['filesPromise', 'serveStaticFile',
  'config.basePath', 'config.urlRoot', 'config.client']

// PUBLIC API
exports.create = createKarmaMiddleware