[
  {
    "path": ".editorconfig",
    "content": "# EditorConfig helps developers define and maintain consistent\n# coding styles between different editors and IDEs\n# editorconfig.org\n\nroot = true\n\n\n[*]\n\n# Change these settings to your own preference\nindent_style = space\nindent_size = 4\n\n# We recommend you to keep these unchanged\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\n\n[*.md]\ntrim_trailing_whitespace = false\n"
  },
  {
    "path": ".gitignore",
    "content": "node_modules\nnpm-debug.log\ntmp\n"
  },
  {
    "path": ".jshintrc",
    "content": "{\n  \"curly\": true,\n  \"eqeqeq\": true,\n  \"immed\": true,\n  \"latedef\": true,\n  \"newcap\": true,\n  \"noarg\": true,\n  \"sub\": true,\n  \"undef\": true,\n  \"boss\": true,\n  \"eqnull\": true,\n  \"node\": true,\n  \"es5\": true\n}\n"
  },
  {
    "path": ".npmignore",
    "content": ""
  },
  {
    "path": "Gruntfile.js",
    "content": "/*\n * grunt-connect-proxy\n * https://github.com/drewzboto/grunt-connect-proxy\n *\n * Copyright (c) 2013 Drewz\n * Licensed under the MIT license.\n */\n\n'use strict';\n\nmodule.exports = function(grunt) {\n\n  var proxySnippet = require(\"./lib/utils.js\").proxyRequest;\n\n  // Project configuration.\n  grunt.initConfig({\n    jshint: {\n      all: [\n        'Gruntfile.js',\n        'tasks/*.js',\n        'lib/*.js',\n        '<%= nodeunit.tests %>'\n      ],\n      options: {\n        jshintrc: '.jshintrc'\n      }\n    },\n\n    // Before generating any new files, remove any previously-created files.\n    clean: {\n      tests: ['tmp']\n    },\n\n    // Configuration to be run (and then tested).\n    connect: {\n      options: {\n          port: 9000,\n          // change this to '0.0.0.0' to access the server from outside\n          hostname: 'localhost'\n      },\n      proxies:\n      [\n            {\n              context: '/defaults',\n              host: 'www.defaults.com'\n            },\n            {\n              context: '/full',\n              host: 'www.full.com',\n              port: 8080,\n              https: true,\n              xforward: true,\n              rewrite: {\n                '^/full': '/anothercontext'\n              },\n              headers: {\n                \"X-Proxied-Header\": \"added\"\n              },\n              ws: true\n            },\n            {\n              context: '/context/test',\n              host: 'www.anothercontext.com',\n              rewrite: {\n                '^/context': '/anothercontext',\n                'test': 'testing'\n              }\n            },\n            {\n              context: '/invalidrewrite',\n              host: 'www.invalidrewrite.com',\n              rewrite: {\n                '^/undefined': undefined,\n                '^/notstring': 13,\n                '^/in': '/thisis'\n              }\n            },\n            {\n              context: '/missinghost'\n            },\n            {\n              host: 'www.missingcontext.com'\n            },\n            {\n              context: ['/array1','/array2'],\n              host: 'www.defaults.com'\n            },\n            {\n              context: '/rewrite',\n              host: 'www.yetanothercontext.com',\n              rewrite: {\n                '^(/)rewrite': function(match, p1) {\n                  return p1;\n                }\n              }\n            }\n      ],\n      server2: {\n        proxies: [\n          {\n            context: '/',\n            host: 'www.server2.com'\n          }\n        ]\n      },\n      server3: {\n        appendProxies: false,\n        proxies: [\n          {\n            context: '/server3',\n            host: 'www.server3.com',\n            port: 8080,\n          }\n        ]\n      },\n      request: {\n        options: {\n          middleware: function (connect, options) {\n            return [require('./lib/utils').proxyRequest];\n          }\n        },\n        proxies: [\n          {\n            context: '/request',\n            host: 'localhost',\n            port: 8080,\n            headers: {\n              \"x-proxied-header\": \"added\"\n            }\n          },\n          {\n            context: '/hideHeaders',\n            host: 'localhost',\n            port: 8081,\n            hideHeaders: ['x-hidden-header-1', 'X-HiDdEn-HeAdEr-2']\n          }\n        ]\n      }\n    },\n\n    // Unit tests.\n    nodeunit: {\n      tests: 'test/connect_proxy_test.js',\n      server2: 'test/server2_proxy_test.js',\n      server3: 'test/server3_proxy_test.js',\n      utils: 'test/utils_test.js',\n      request: 'test/request_test.js',\n      hideHeaders: 'test/hide_headers_test.js'\n    }\n\n  });\n\n  // Actually load this plugin's task(s).\n  grunt.loadTasks('tasks');\n\n  // These plugins provide necessary tasks.\n  grunt.loadNpmTasks('grunt-contrib-connect');\n  grunt.loadNpmTasks('grunt-contrib-jshint');\n  grunt.loadNpmTasks('grunt-contrib-clean');\n  grunt.loadNpmTasks('grunt-contrib-nodeunit');\n\n  // Whenever the \"test\" task is run, first clean the \"tmp\" dir, then run this\n  // plugin's task(s), then test the result.\n  grunt.registerTask('test', [\n    'clean',\n    'nodeunit:utils',\n    'configureProxies',\n    'nodeunit:tests',\n    'configureProxies:server2',\n    'nodeunit:server2',\n    'configureProxies:server3',\n    'nodeunit:server3',\n    'configureProxies:request',\n    'connect:request',\n    'nodeunit:request',\n    'nodeunit:hideHeaders'\n    ]);\n\n  // specifically test that option inheritance works for multi-level config\n  grunt.registerTask('test-inheritance', [\n    'clean',\n    'configureProxies:server2',\n    'nodeunit:server2'\n  ]);\n\n\n  // By default, lint and run all tests.\n  grunt.registerTask('default', ['jshint', 'test']);\n\n};\n"
  },
  {
    "path": "LICENSE-MIT",
    "content": "Copyright (c) 2013 Drewz\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# grunt-connect-proxy\n\n> Provides a http proxy as middleware for the grunt-contrib-connect plugin.\n\n## Getting Started\nThis plugin requires Grunt `~0.4.1`\n\nIf you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:\n\n```shell\nnpm install grunt-connect-proxy --save-dev\n```\n\nOne the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:\n\n```js\ngrunt.loadNpmTasks('grunt-connect-proxy');\n```\n\n## Adapting the  \"connect\" task\n\n### Overview\n\n#### Proxy Configuration\nIn your project's Gruntfile, add a section named `proxies` to your existing connect definition.\n\n```js\ngrunt.initConfig({\n    connect: {\n        server: {\n            options: {\n                port: 9000,\n                hostname: 'localhost'\n            },\n            proxies: [\n                {\n                    context: '/cortex',\n                    host: '10.10.2.202',\n                    port: 8080,\n                    https: false,\n                    xforward: false,\n                    headers: {\n                        \"x-custom-added-header\": value\n                    },\n                    hideHeaders: ['x-removed-header']\n                }\n            ]\n        }\n    }\n})\n```\n#### Adding the middleware\n\n##### With Livereload\n\nAdd the middleware call from the connect option middleware hook\n```js\n        connect: {\n            livereload: {\n                options: {\n                    middleware: function (connect, options) {\n                        if (!Array.isArray(options.base)) {\n                            options.base = [options.base];\n                        }\n\n                        // Setup the proxy\n                        var middlewares = [require('grunt-connect-proxy/lib/utils').proxyRequest];\n\n                        // Serve static files.\n                        options.base.forEach(function(base) {\n                            middlewares.push(connect.static(base));\n                        });\n\n                        // Make directory browse-able.\n                        var directory = options.directory || options.base[options.base.length - 1];\n                        middlewares.push(connect.directory(directory));\n\n                        return middlewares;\n                    }\n                }\n            }\n        }\n```\n\n##### Without Livereload\n\nIt is possible to add the proxy middleware without Livereload as follows:\n\n```js\n   // server\n    connect: {\n      server: {\n        options: {\n          port: 8000,\n          base: 'public',\n          logger: 'dev',\n          hostname: 'localhost',\n          middleware: function (connect, options, defaultMiddleware) {\n             var proxy = require('grunt-connect-proxy/lib/utils').proxyRequest;\n             return [\n                // Include the proxy first\n                proxy\n             ].concat(defaultMiddleware);\n          }\n        },\n        proxies: [ /* as defined above */ ]\n      }\n  }\n```\n\n### Adding the configureProxy task to the server task\nFor the server task, add the configureProxies task before the connect task\n```js\n    grunt.registerTask('server', function (target) {\n        grunt.task.run([\n            'clean:server',\n            'compass:server',\n            'configureProxies:server',\n            'livereload-start',\n            'connect:livereload',\n            'open',\n            'watch'\n        ]);\n    });\n```\n\n**IMPORTANT**: You must specify the connect target in the `configureProxies` task.\n\n### Options\nThe available configuration options from a given proxy are generally the same as what is provided by the underlying [httpproxy](https://github.com/nodejitsu/node-http-proxy) library\n\n#### options.context\nType: `String` or `Array`\n\nThe context(s) to match requests against. Matching requests will be proxied. Should start with /. Should not end with /\nMultiple contexts can be matched for the same proxy rule via an array such as:\ncontext: ['/api', '/otherapi']\n\n#### options.host\nType: `String`\n\nThe host to proxy to. Should not start with the http/https protocol.\n\n#### options.port\nType: `Number`\nDefault: 80\n\nThe port to proxy to.\n\n#### options.https\nType: `Boolean`\nDefault: false\n\n if the proxy should target a https end point on the destination server\n\n#### options.secure\nType: `Boolean`\nDefault: true\n\n true/false, if you want to verify the SSL Certs (Avoids: SELF_SIGNED_CERT_IN_CHAIN errors when set to false)\n\nWhether to proxy with https\n\n#### options.xforward:\nType: `Boolean`\nDefault: false\n\nWhether to add x-forward headers to the proxy request, such as\n  \"x-forwarded-for\": \"127.0.0.1\",\n  \"x-forwarded-port\": 50892,\n  \"x-forwarded-proto\": \"http\"\n\n\n#### options.appendProxies\nType: `Boolean`\nDefault: true\n\nSet to false to isolate multi-task configuration proxy options from parent level instead of appending them.\n\n#### options.rewrite\nType: `Object`\n\nAllows rewrites of url (including context) when proxying. The object's keys serve as the regex used in the replacement operation. As an example the following proxy configuration will update the context when proxying:\n\n```js\nproxies: [\n    context: '/context',\n    host: 'host',\n    port: 8080,\n    rewrite: {\n        '^/removingcontext': '',\n        '^/changingcontext': '/anothercontext',\n        '^/updating(context)': function(match, p1) {\n            return '/new' + p1;\n        }\n    }\n]\n```\n\n#### options.headers\nType: `Object`\n\nA map of headers to be added to proxied requests.\n\n#### options.hostRewrite\nType: `String`\n\nRewrites the location hostname on 30X redirects.\n\n#### options.hideHeaders\nType: `Array`\n\nAn array of headers that should be removed from the server's response.\n\n#### options.errorHandler\nType: `Function`\n\nAnother middleware that will be called if proxy request fails.\nExample:\n```js\n    errorHandler: function(req, res, next, err) {\n        if (err.code === 404) {\n            res.send('Some error page');\n        } else {\n            next();\n        }\n    }\n```\n\n#### options.ws\nType: `Boolean`\nDefault: false\n\nSet to true to proxy websockets.\n\n## Contributing\nIn lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).\n\n#### Multi-server proxy configuration\n\ngrunt-contrib-connect multi-server configuration is supported. You can define _proxies_ blocks in per-server options and refer to those blocks in task invocation.\n\n```js\ngrunt.initConfig({\n    connect: {\n            options: {\n                port: 9000,\n                hostname: 'localhost'\n            },\n            server2: {\n                proxies: [\n                    {\n                        context: '/cortex',\n                        host: '10.10.2.202',\n                        port: 8080,\n                        https: false,\n                    }\n                ]\n            },\n            server3: {\n                appendProxies: false,\n                proxies: [\n                    {\n                        context: '/api',\n                        host: 'example.org'\n                    }\n                ]\n            }\n        }\n})\n\ngrunt.registerTask('e2etest', function (target) {\n    grunt.task.run([\n        'configureProxies:server2',\n        'open',\n        'karma'\n    ]);\n});\n```\n\n\n## Release History\n* 0.1.0 Initial release\n* 0.1.1 Fix changeOrigin\n* 0.1.2 Support multiple server definitions, bumped to grunt 0.4.1 (thanks to @lauripiispanen)\n* 0.1.3 Bumped http-proxy dependency to 0.10.2\n* 0.1.4 Added proxy rewrite support (thanks to @slawrence)\n* 0.1.5 Default rejectUnauthorized to false to allow self-signed certificates over SSL\n* 0.1.6 Add xforward option, added support for context arrays, added debug logging\n* 0.1.7 Added WebSocket support (thanks for @killfill), Headers support (thanks to @gadr), various docs fixed\n* 0.1.8 Minor websocket bug fix\n* 0.1.10 Minor bug fix\n* 0.1.11 Fix Websocket support on Node 0.10 - Bumped http-proxy dependency to 1.1.4, Removed unsupported http-proxy options (rejectUnauthorized, timeout, changeOrigin)\n* 0.2.0 Added hidden headers support\n"
  },
  {
    "path": "examples/sample.yeoman.grunt.js",
    "content": "// Generated on 2013-02-28 using generator-webapp 0.1.5\n'use strict';\nvar lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;\nvar mountFolder = function (connect, dir) {\n    return connect.static(require('path').resolve(dir));\n};\nvar proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;\n\n// # Globbing\n// for performance reasons we're only matching one level down:\n// 'test/spec/{,*/}*.js'\n// use this if you want to match all subfolders:\n// 'test/spec/**/*.js'\n\nmodule.exports = function (grunt) {\n    // load all grunt tasks\n    require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);\n\n    // configurable paths\n    var yeomanConfig = {\n        app: 'app',\n        dist: 'dist'\n    };\n\n    grunt.initConfig({\n        yeoman: yeomanConfig,\n        watch: {\n            compass: {\n                files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],\n                tasks: ['compass']\n            },\n            livereload: {\n                files: [\n                    '<%= yeoman.app %>/*.html',\n                    '{.tmp,<%= yeoman.app %>}/styles/{,*/}*.css',\n                    '{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',\n                    '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,webp}'\n                ],\n                tasks: ['livereload']\n            }\n        },\n        connect: {\n            options: {\n                port: 9000,\n                // change this to '0.0.0.0' to access the server from outside\n                hostname: 'localhost'\n            },\n            proxies: [\n                {\n                    context: '/cortex',\n                    host: 'localhost',\n                    port: 8080\n                }\n            ],\n            livereload: {\n                options: {\n                    middleware: function (connect) {\n                        return [\n                            proxySnippet,\n                            lrSnippet,\n                            mountFolder(connect, '.tmp'),\n                            mountFolder(connect, 'app')\n                        ];\n                    }\n                }\n            },\n            test: {\n                options: {\n                    middleware: function (connect) {\n                        return [\n                            mountFolder(connect, '.tmp'),\n                            mountFolder(connect, 'test')\n                        ];\n                    }\n                }\n            },\n            dist: {\n                options: {\n                    middleware: function (connect) {\n                        return [\n                            mountFolder(connect, 'dist')\n                        ];\n                    }\n                }\n            }\n        },\n        open: {\n            server: {\n                path: 'http://localhost:<%= connect.options.port %>'\n            }\n        },\n        clean: {\n            dist: ['.tmp', '<%= yeoman.dist %>/*'],\n            server: '.tmp'\n        },\n        jshint: {\n            options: {\n                jshintrc: '.jshintrc'\n            },\n            all: [\n                'Gruntfile.js',\n                '<%= yeoman.app %>/scripts/{,*/}*.js',\n                '!<%= yeoman.app %>/scripts/vendor/*',\n                'test/spec/{,*/}*.js'\n            ]\n        },\n        mocha: {\n            all: {\n                options: {\n                    run: true,\n                    urls: ['http://localhost:<%= connect.options.port %>/index.html']\n                }\n            }\n        },\n        compass: {\n            options: {\n                sassDir: '<%= yeoman.app %>/styles',\n                cssDir: '.tmp/styles',\n                imagesDir: '<%= yeoman.app %>/images',\n                javascriptsDir: '<%= yeoman.app %>/scripts',\n                fontsDir: '<%= yeoman.app %>/styles/fonts',\n                importPath: 'app/components',\n                relativeAssets: true\n            },\n            dist: {},\n            server: {\n                options: {\n                    debugInfo: true\n                }\n            }\n        },\n        // not used since Uglify task does concat,\n        // but still available if needed\n        /*concat: {\n            dist: {}\n        },*/\n        requirejs: {\n            dist: {\n                // Options: https://github.com/jrburke/r.js/blob/master/build/example.build.js\n                options: {\n                    // `name` and `out` is set by grunt-usemin\n                    baseUrl: 'app/scripts',\n                    optimize: 'none',\n                    // TODO: Figure out how to make sourcemaps work with grunt-usemin\n                    // https://github.com/yeoman/grunt-usemin/issues/30\n                    //generateSourceMaps: true,\n                    // required to support SourceMaps\n                    // http://requirejs.org/docs/errors.html#sourcemapcomments\n                    preserveLicenseComments: false,\n                    useStrict: true,\n                    wrap: true,\n                    //uglify2: {} // https://github.com/mishoo/UglifyJS2\n                }\n            }\n        },\n        useminPrepare: {\n            html: '<%= yeoman.app %>/index.html',\n            options: {\n                dest: '<%= yeoman.dist %>'\n            }\n        },\n        usemin: {\n            html: ['<%= yeoman.dist %>/{,*/}*.html'],\n            css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],\n            options: {\n                dirs: ['<%= yeoman.dist %>']\n            }\n        },\n        imagemin: {\n            dist: {\n                files: [{\n                    expand: true,\n                    cwd: '<%= yeoman.app %>/images',\n                    src: '{,*/}*.{png,jpg,jpeg}',\n                    dest: '<%= yeoman.dist %>/images'\n                }]\n            }\n        },\n        cssmin: {\n            dist: {\n                files: {\n                    '<%= yeoman.dist %>/styles/main.css': [\n                        '.tmp/styles/{,*/}*.css',\n                        '<%= yeoman.app %>/styles/{,*/}*.css'\n                    ]\n                }\n            }\n        },\n        htmlmin: {\n            dist: {\n                options: {\n                    /*removeCommentsFromCDATA: true,\n                    // https://github.com/yeoman/grunt-usemin/issues/44\n                    //collapseWhitespace: true,\n                    collapseBooleanAttributes: true,\n                    removeAttributeQuotes: true,\n                    removeRedundantAttributes: true,\n                    useShortDoctype: true,\n                    removeEmptyAttributes: true,\n                    removeOptionalTags: true*/\n                },\n                files: [{\n                    expand: true,\n                    cwd: '<%= yeoman.app %>',\n                    src: '*.html',\n                    dest: '<%= yeoman.dist %>'\n                }]\n            }\n        },\n        copy: {\n            dist: {\n                files: [{\n                    expand: true,\n                    dot: true,\n                    cwd: '<%= yeoman.app %>',\n                    dest: '<%= yeoman.dist %>',\n                    src: [\n                        '*.{ico,txt}',\n                        '.htaccess'\n                    ]\n                }]\n            }\n        },\n        bower: {\n            all: {\n                rjsConfig: '<%= yeoman.app %>/scripts/main.js'\n            }\n        }\n    });\n\n    grunt.renameTask('regarde', 'watch');\n\n    grunt.registerTask('server', function (target) {\n        if (target === 'dist') {\n            return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);\n        }\n\n        grunt.task.run([\n            'clean:server',\n            'compass:server',\n            'configureProxies',\n            'livereload-start',\n            'connect:livereload',\n            'open',\n            'watch'\n        ]);\n    });\n\n    grunt.registerTask('test', [\n        'clean:server',\n        'compass',\n        'connect:test',\n        'mocha'\n    ]);\n\n    grunt.registerTask('build', [\n        'clean:dist',\n        'compass:dist',\n        'useminPrepare',\n        'requirejs',\n        'imagemin',\n        'htmlmin',\n        'concat',\n        'cssmin',\n        'uglify',\n        'copy',\n        'usemin'\n    ]);\n\n    grunt.registerTask('default', [\n        'jshint',\n        'test',\n        'build'\n    ]);\n};\n"
  },
  {
    "path": "lib/utils.js",
    "content": "'use strict';\nvar utils = module.exports;\nvar httpProxy = require('http-proxy');\nvar grunt = require('grunt');\nvar _ = require('lodash');\nvar proxies = [];\nvar rewrite = function (req) {\n    return function (rule) {\n        if (rule.from.test(req.url)) {\n            req.url = req.url.replace(rule.from, rule.to);\n        }\n    };\n};\n\nutils.registerProxy = function(proxy) {\n    proxies.push(proxy);\n};\n\nutils.proxies = function() {\n    return proxies;\n};\n\nutils.reset = function() {\n    proxies = [];\n};\n\nutils.validateRewrite = function (rule) {\n    if (!rule ||\n        typeof rule.from === 'undefined' ||\n        typeof rule.to === 'undefined' ||\n        typeof rule.from !== 'string' ||\n        (typeof rule.to !== 'string' && typeof rule.to !== 'function')) {\n        return false;\n    }\n    return true;\n};\n\nutils.processRewrites = function (rewrites) {\n    var rules = [];\n\n    Object.keys(rewrites || {}).forEach(function (from) {\n        var rule = {\n            from: from,\n            to: rewrites[from]\n        };\n\n        if (utils.validateRewrite(rule)) {\n            rule.from = new RegExp(rule.from);\n            rules.push(rule);\n            grunt.log.writeln('Rewrite rule created for: [' + rule.from + ' -> ' + rule.to + '].');\n        } else {\n            grunt.log.error('Invalid rule');\n        }\n    });\n\n    return rules;\n};\n\nutils.matchContext = function(context, url) {\n    var positiveContexts, negativeContexts, positiveMatch, negativeMatch;\n    var contexts = context;\n    if (!_.isArray(contexts)) {\n        contexts = [contexts];\n    }\n    positiveContexts = _.filter(contexts, function(c){return c.charAt(0) !== '!';});\n    negativeContexts = _.filter(contexts, function(c){return c.charAt(0) === '!';});\n    // Remove the '!' character from the contexts\n    negativeContexts = _.map(negativeContexts, function(c){return c.slice(1);});\n    negativeMatch = _.find(negativeContexts, function(c){return url.lastIndexOf(c, 0) === 0;});\n    // If any context negates this url, it must not be proxied.\n    if (negativeMatch) {\n        return false;\n    }\n    positiveMatch = _.find(positiveContexts, function(c){return url.lastIndexOf(c, 0) === 0;});\n    // If there is any positive match, lets proxy this url.\n    return positiveMatch != null;\n};\n\nutils.getTargetUrl = function(options){\n    var protocol = options.ws ? 'ws' : 'http';\n    if(options.https) {\n        protocol += 's';\n    }\n\n    var target = protocol + '://' + options.host;\n    var standardPort = (options.port === 80 && !options.https) || (options.port === 443 && options.https);\n\n    if(!standardPort){\n        target += ':' + options.port;\n    }\n    return target;\n};\n\nfunction onUpgrade(req, socket, head) {\n    var proxied = false;\n\n    proxies.forEach(function(proxy) {\n        if (!proxied && req && proxy.config.ws && utils.matchContext(proxy.config.context, req.url)) {\n            if (proxy.config.rules.length) {\n                proxy.config.rules.forEach(rewrite(req));\n            }\n            proxy.server.ws(req, socket, head);\n\n            proxied = true;\n\n            var source = req.url;\n            var target = utils.getTargetUrl(proxy.config) + req.url;\n            grunt.log.verbose.writeln('[WS] Proxied request: ' + source + ' -> ' + target + '\\n' + JSON.stringify(req.headers, true, 2));\n        }\n    });\n}\n\n//Listen for the update event,onces. grunt-contrib-connect doesnt expose the server object, so bind after the first req\nfunction enableWebsocket(server) {\n    if (server && !server.proxyWs) {\n        server.proxyWs = true;\n        grunt.log.verbose.writeln('[WS] Catching upgrade event...');\n        server.on('upgrade', onUpgrade);\n    }\n}\n\nfunction removeHiddenHeaders(proxy) {\n    var hiddenHeaders = proxy.config.hideHeaders;\n\n    if(hiddenHeaders && hiddenHeaders.length > 0) {\n        hiddenHeaders = hiddenHeaders.map(function(header) {\n          return header.toLowerCase();\n        });\n\n        proxy.server.on('proxyRes', function(proxyRes) {\n            var headers = proxyRes.headers;\n            hiddenHeaders.forEach(function(header) {\n                if(header in headers) {\n                    delete headers[header];\n                }\n            });\n        });\n    }\n}\n\nutils.proxyRequest = function (req, res, next) {\n    var proxied = false;\n\n    enableWebsocket(req.connection.server);\n\n    proxies.forEach(function(proxy) {\n        if (!proxied && req && utils.matchContext(proxy.config.context, req.url)) {\n            if (proxy.config.rules.length) {\n                proxy.config.rules.forEach(rewrite(req));\n            }\n            // Add headers present in the config object\n            if (proxy.config.headers != null) {\n                _.forOwn(proxy.config.headers, function(value, key) {\n                    req.headers[key] = value;\n                });\n            }\n\n            proxy.server.proxyRequest(req, res, proxy.server, function(err) {\n                if (proxy.config.errorHandler) {\n                    grunt.log.verbose.writeln('Request failed. Skipping to next midleware.');\n                    proxy.config.errorHandler(req, res, next, err);\n                }\n            });\n            removeHiddenHeaders(proxy);\n\n            // proxying twice would cause the writing to a response header that is already sent. Bad config!\n            proxied = true;\n\n            var source = req.originalUrl;\n            var target = utils.getTargetUrl(proxy.config) + req.url;\n            grunt.log.verbose.writeln('Proxied request: ' + source + ' -> ' + target + '\\n' + JSON.stringify(req.headers, true, 2));\n        }\n    });\n    if (!proxied) {\n        next();\n    }\n};\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"grunt-connect-proxy\",\n  \"description\": \"Provides a http proxy as middleware for grunt connect.\",\n  \"version\": \"0.2.0\",\n  \"homepage\": \"https://github.com/drewzboto/grunt-connect-proxy\",\n  \"author\": {\n    \"name\": \"Drewz\",\n    \"email\": \"drewz@2mod5.com\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git://github.com/drewzboto/grunt-connect-proxy.git\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/drewzboto/grunt-connect-proxy/issues\"\n  },\n  \"licenses\": [\n    {\n      \"type\": \"MIT\",\n      \"url\": \"https://github.com/drewzboto/grunt-connect-proxy/blob/master/LICENSE-MIT\"\n    }\n  ],\n  \"main\": \"Gruntfile.js\",\n  \"engines\": {\n    \"node\": \">= 0.10.0\"\n  },\n  \"scripts\": {\n    \"test\": \"grunt test\"\n  },\n  \"dependencies\": {\n    \"http-proxy\": \"~1.11.0\",\n    \"lodash\": \"~0.9.0\"\n  },\n  \"devDependencies\": {\n    \"grunt-contrib-jshint\": \"~0.1.1\",\n    \"grunt-contrib-clean\": \"~0.4.0\",\n    \"grunt-contrib-nodeunit\": \"~0.4.1\",\n    \"grunt\": \"~0.4.1\",\n    \"grunt-contrib-connect\": \"~0.5.0\"\n  },\n  \"peerDependencies\": {\n    \"grunt\": \"~0.4.1\"\n  },\n  \"keywords\": [\n    \"gruntplugin\",\n    \"proxy\",\n    \"connect\",\n    \"http\",\n    \"grunt\"\n  ]\n}\n"
  },
  {
    "path": "tasks/connect_proxy.js",
    "content": "/*\n * grunt-connect-proxy\n * https://github.com/drewzboto/grunt-connect-proxy\n *\n * Copyright (c) 2013 Drewz\n * Licensed under the MIT license.\n */\n\n'use strict';\nvar utils = require('../lib/utils');\nvar _ = require('lodash');\n\nmodule.exports = function(grunt) {\n  grunt.registerTask('configureProxies', 'Configure any specified connect proxies.', function(config) {\n    // setup proxy\n    var httpProxy = require('http-proxy');\n    var proxyOption;\n    var proxyOptions = [];\n    var validateProxyConfig = function(proxyOption) {\n        if (_.isUndefined(proxyOption.host) || _.isUndefined(proxyOption.context)) {\n            grunt.log.error('Proxy missing host or context configuration');\n            return false;\n        }\n        if (proxyOption.https && proxyOption.port === 80) {\n            grunt.log.warn('Proxy  for ' + proxyOption.context + ' is using https on port 80. Are you sure this is correct?');\n        }\n        return true;\n    };\n\n    utils.reset();\n    utils.log = grunt.log;\n    if (config) {\n        var connectOptions = grunt.config('connect.'+config) || [];\n        if (typeof connectOptions.appendProxies === 'undefined' || connectOptions.appendProxies) {\n            proxyOptions = proxyOptions.concat(grunt.config('connect.proxies') || []);\n        }\n        proxyOptions = proxyOptions.concat(connectOptions.proxies || []);\n    } else {\n        proxyOptions = proxyOptions.concat(grunt.config('connect.proxies') || []);\n    }\n    proxyOptions.forEach(function(proxy) {\n        proxyOption = _.defaults(proxy,  {\n            port: proxy.https ? 443 : 80,\n            https: false,\n            secure: true,\n            xforward: false,\n            rules: [],\n            errorHandler: function(req, res, next) {  },\n            ws: false\n        });\n        if (validateProxyConfig(proxyOption)) {\n            proxyOption.rules = utils.processRewrites(proxyOption.rewrite);\n            utils.registerProxy({\n                server: httpProxy.createProxyServer({\n                    target: utils.getTargetUrl(proxyOption),\n                    secure: proxyOption.secure,\n                    xfwd: proxyOption.xforward,\n                    headers: {\n                        host: proxyOption.host\n                    },\n                    hostRewrite: proxyOption.hostRewrite\n                }).on('error', function (err, req, res) {\n                    grunt.log.error('Proxy error: ', err.code);\n                }),\n                config: proxyOption\n            });\n            grunt.log.writeln('Proxy created for: ' +  proxyOption.context + ' to ' + proxyOption.host + ':' + proxyOption.port);\n        }\n    });\n  });\n};\n"
  },
  {
    "path": "test/connect_proxy_test.js",
    "content": "'use strict';\n\nvar grunt = require('grunt');\n\n/*\n  ======== A Handy Little Nodeunit Reference ========\n  https://github.com/caolan/nodeunit\n\n  Test methods:\n    test.expect(numAssertions)\n    test.done()\n  Test assertions:\n    test.ok(value, [message])\n    test.equal(actual, expected, [message])\n    test.notEqual(actual, expected, [message])\n    test.deepEqual(actual, expected, [message])\n    test.notDeepEqual(actual, expected, [message])\n    test.strictEqual(actual, expected, [message])\n    test.notStrictEqual(actual, expected, [message])\n    test.throws(block, [error], [message])\n    test.doesNotThrow(block, [error], [message])\n    test.ifError(value)\n*/\nvar utils = require(\"../lib/utils.js\");\n\nexports.connect_proxy = {\n  setUp: function(done) {\n    // setup here if necessary\n    done();\n  },\n  default_options: function(test) {\n    test.expect(8);\n    var proxies = utils.proxies();\n\n    test.equal(proxies.length, 6, 'should return six valid proxies');\n    test.notEqual(proxies[0].server, null, 'server should be configured');\n    test.equal(proxies[0].config.context, '/defaults', 'should have context set from config');\n    test.equal(proxies[0].config.host, 'www.defaults.com', 'should have host set from config');\n    test.equal(proxies[0].config.port, 80, 'should have default port 80');\n    test.equal(proxies[0].config.https, false, 'should have default http');\n    test.equal(proxies[0].config.xforward, false, 'should have default xforward');\n    test.equal(proxies[0].config.ws, false, 'should have default ws to false');\n\n    test.done();\n  },\n  full_options: function(test) {\n    test.expect(11);\n    var proxies = utils.proxies();\n\n    test.equal(proxies.length, 6, 'should return five valid proxies');\n    test.notEqual(proxies[1].server, null, 'server should be configured');\n    test.equal(proxies[1].config.context, '/full', 'should have context set from config');\n    test.equal(proxies[1].config.host, 'www.full.com', 'should have host set from config');\n    test.equal(proxies[1].config.port, 8080, 'should have port set from config');\n    test.equal(proxies[1].config.https, true, 'should have http set from config');\n    test.equal(proxies[1].config.xforward, true, 'should have xforward set from config');\n    test.equal(proxies[1].config.ws, true, 'should have ws set from config');\n    test.deepEqual(proxies[1].config.rewrite, { '^/full': '/anothercontext' }, 'should have rewrite set from config');\n    test.equal(proxies[1].config.rules.length, 1, 'rules array should have an item');\n    test.deepEqual(proxies[1].config.rules[0], { from: new RegExp('^/full'), to: '/anothercontext'}, 'rules object should be converted to regex');\n\n    test.done();\n  },\n\n  two_rewrites: function(test) {\n    test.expect(2);\n    var config = utils.proxies()[2].config;\n    test.equal(config.rules.length, 2, 'rules array should have two items');\n    test.deepEqual(config.rewrite, { '^/context': '/anothercontext', 'test': 'testing' }, 'should have rewrite set from config');\n\n    test.done();\n  },\n\n  invalid_configs: function(test) {\n    test.expect(5);\n    var proxies = utils.proxies();\n\n    test.equal(proxies.length, 6, 'should not add the 2 invalid proxies');\n    test.notEqual(proxies[0].config.context, '/missinghost', 'should not have context set from config with missing host');\n    test.notEqual(proxies[0].config.host, 'www.missingcontext.com', 'should not have host set from config with missing context');\n    test.notEqual(proxies[1].config.context, '/missinghost', 'should not have context set from config with missing host');\n    test.notEqual(proxies[1].config.host, 'www.missingcontext.com', 'should not have host set from config with missing context');\n    test.done();\n  },\n\n  invalid_rewrite: function(test) {\n    test.expect(3);\n    var proxies = utils.proxies();\n    test.equal(proxies.length, 6, 'proxies should still be valid');\n    test.equal(proxies[3].config.rules.length, 1, 'rules array should have one valid item');\n    test.deepEqual(proxies[3].config.rules[0], { from: new RegExp('^/in'), to: '/thisis'}, 'rules object should be converted to regex');\n\n    test.done();\n  },\n\n  function_rewrite: function(test) {\n    test.expect(1);\n    console.log(utils.proxies());\n    var proxies = utils.proxies(),\n        rules = proxies[5].config.rules[0];\n    test.equal('/rewrite'.replace(rules.from, rules.to), '/', 'should execute function when replacing');\n    test.done();\n  },\n};\n"
  },
  {
    "path": "test/hide_headers_test.js",
    "content": "'use strict';\n\nvar utils = require(\"../lib/utils.js\");\nvar http = require('http');\n\nexports.connect_proxy = {\n  setUp: function(done) {\n    // setup here if necessary\n    done();\n  },\n  proxied_request: function(test) {\n    test.expect(2);\n    http.createServer(function (req, res) {\n      res.writeHead(200, {\n        'x-hidden-header-1': 'this header should be removed',\n        'x-hidden-header-2': 'this header should also be removed'\n      });\n      res.end();\n    }).listen(8081);\n\n    http.request({\n      host: 'localhost',\n      path: '/hideHeaders',\n      port: 9000\n    }, function(response) {\n\n      test.equal(response.headers['x-hidden-header-1'], undefined, 'hidden header should be hidden');\n      test.equal(response.headers['x-hidden-header-2'], undefined, 'header hiding is case insensitive');\n      test.done();\n    }).end();\n  }\n};\n"
  },
  {
    "path": "test/request_test.js",
    "content": "'use strict';\n\n/*\n  ======== A Handy Little Nodeunit Reference ========\n  https://github.com/caolan/nodeunit\n\n  Test methods:\n    test.expect(numAssertions)\n    test.done()\n  Test assertions:\n    test.ok(value, [message])\n    test.equal(actual, expected, [message])\n    test.notEqual(actual, expected, [message])\n    test.deepEqual(actual, expected, [message])\n    test.notDeepEqual(actual, expected, [message])\n    test.strictEqual(actual, expected, [message])\n    test.notStrictEqual(actual, expected, [message])\n    test.throws(block, [error], [message])\n    test.doesNotThrow(block, [error], [message])\n    test.ifError(value)\n*/\nvar utils = require(\"../lib/utils.js\");\nvar http = require('http');\n\nexports.connect_proxy = {\n  setUp: function(done) {\n    // setup here if necessary\n    done();\n  },\n  proxied_request: function(test) {\n    test.expect(2);\n    http.createServer(function (req, res) {\n      test.equal(req.headers[\"x-proxied-header\"], 'added', 'headers should be added to request');\n      res.writeHead(200, { 'Content-Type': 'text/plain' });\n      res.write('request successfully proxied!');\n      res.end();\n    }).listen(8080);\n\n    http.request({\n      host: 'localhost',\n      path: '/request',\n      port: 9000\n    }, function(response) {\n      var data = '';\n      response.on('data', function (chunk) {\n        data += chunk;\n      });\n      response.on('end', function () {\n        test.equal(data, 'request successfully proxied!', 'request should be received');\n        test.done();\n      });\n    }).end();\n  }\n};\n"
  },
  {
    "path": "test/server2_proxy_test.js",
    "content": "var utils = require(\"../lib/utils.js\");\n\nexports.server2_proxy_test = {\n  setUp: function(done) {\n    // setup here if necessary\n    done();\n  },\n  proxy_options_test: function(test) {\n    test.expect(10);\n    var proxies = utils.proxies();\n\n    test.equal(proxies.length, 7, 'should return seven valid proxies');\n    test.notEqual(proxies[0].server, null, 'server should be configured');\n    test.equal(proxies[0].config.context, '/defaults', 'should have context set from config');\n    test.equal(proxies[0].config.host, 'www.defaults.com', 'should have host set from config');\n    test.equal(proxies[6].config.context, '/', 'should have context set from config');\n    test.equal(proxies[6].config.host, 'www.server2.com', 'should have host set from config');\n    test.equal(proxies[0].config.port, 80, 'should have default port 80');\n    test.equal(proxies[0].config.https, false, 'should have default http');\n    test.equal(proxies[0].config.ws, false, 'should have default ws to false');\n    test.equal(proxies[0].config.rules.length, 0, 'rules array should have zero items');\n\n    test.done();\n  }\n}\n"
  },
  {
    "path": "test/server3_proxy_test.js",
    "content": "var utils = require(\"../lib/utils.js\");\n\nexports.server3_proxy_test = {\n  setUp: function(done) {\n    // setup here if necessary\n    done();\n  },\n  proxy_options_test: function(test) {\n    test.expect(8);\n    var proxies = utils.proxies();\n\n    test.equal(proxies.length, 1, 'should have just one proxy');\n    test.notEqual(proxies[0].server, null, 'server should be configured');\n    test.equal(proxies[0].config.context, '/server3', 'should have context set from config');\n    test.equal(proxies[0].config.host, 'www.server3.com', 'should have host set from config');\n    test.equal(proxies[0].config.port, 8080, 'should have port 8080');\n    test.equal(proxies[0].config.https, false, 'should have default http');\n    test.equal(proxies[0].config.ws, false, 'should have ws default to false');\n    test.equal(proxies[0].config.rules.length, 0, 'rules array should have zero items');\n\n    test.done();\n  }\n}\n"
  },
  {
    "path": "test/utils_test.js",
    "content": "var utils = require(\"../lib/utils.js\");\n\nexports.utils_test = {\n  setUp: function(done) {\n    // setup here if necessary\n    done();\n  },\n  match_context_test: function(test) {\n    var singleContext, arrayContext, url, match;\n    test.expect(6);\n\n    singleContext = '/api';\n    url = '/api/mock?suchrequest=1';\n    match = utils.matchContext(singleContext, url);\n    test.equal(match, true, 'should match single context with matching start');\n\n    url = '/notapi/mock?suchrequest=1';\n    match = utils.matchContext(singleContext, url);\n    test.equal(match, false, 'should not match single context with different start');\n\n    arrayContext = ['/api', '/superapi'];\n    url = '/superapi/mock?suchrequest=1';\n    match = utils.matchContext(arrayContext, url);\n    test.equal(match, true, 'should match array context with matching start');\n\n    singleContext = '/api';\n    url = '/api/mock/api';\n    match = utils.matchContext(singleContext, url);\n    test.equal(match, true, 'should match array context with matching start if same pattern is found later');\n\n    arrayContext = ['/api', '/superapi', '!/superapi/not'];\n    url = '/superapi/not/mock?suchrequest=1';\n    match = utils.matchContext(arrayContext, url);\n    test.equal(match, false, 'should not match array context with negative context');\n\n    arrayContext = ['/api', '/superapi', '!/superapi/not'];\n    url = '/superapi/yep/mock?suchrequest=1';\n    match = utils.matchContext(arrayContext, url);\n    test.equal(match, true, 'should match array context with different negative context');\n\n    test.done();\n  },\n\n  get_target_url_test: function(test){\n    var proxyOptions = {\n        host: 'foo.com',\n        https: true,\n        port: 443,\n        ws: false\n    };\n\n    test.expect(6);\n    test.equal(utils.getTargetUrl(proxyOptions), 'https://foo.com');\n\n    proxyOptions.https = false;\n    proxyOptions.port = 80;\n    test.equal(utils.getTargetUrl(proxyOptions), 'http://foo.com');\n\n    proxyOptions.ws = true;\n    test.equal(utils.getTargetUrl(proxyOptions), 'ws://foo.com');\n\n    proxyOptions.https = true;\n    proxyOptions.port = 443\n    test.equal(utils.getTargetUrl(proxyOptions), 'wss://foo.com');\n\n    proxyOptions.port = 8080;\n    proxyOptions.ws = false;\n    proxyOptions.https = false;\n    test.equal(utils.getTargetUrl(proxyOptions), 'http://foo.com:8080');\n\n    proxyOptions.port = 445;\n    proxyOptions.ws = false;\n    proxyOptions.https = true;\n    test.equal(utils.getTargetUrl(proxyOptions), 'https://foo.com:445');\n\n    test.done();\n  }\n};\n"
  }
]