master 3e212633bb95 cached
17 files
42.9 KB
10.5k tokens
3 symbols
1 requests
Download .txt
Repository: drewzboto/grunt-connect-proxy
Branch: master
Commit: 3e212633bb95
Files: 17
Total size: 42.9 KB

Directory structure:
gitextract_n_5bk1va/

├── .editorconfig
├── .gitignore
├── .jshintrc
├── .npmignore
├── Gruntfile.js
├── LICENSE-MIT
├── README.md
├── examples/
│   └── sample.yeoman.grunt.js
├── lib/
│   └── utils.js
├── package.json
├── tasks/
│   └── connect_proxy.js
└── test/
    ├── connect_proxy_test.js
    ├── hide_headers_test.js
    ├── request_test.js
    ├── server2_proxy_test.js
    ├── server3_proxy_test.js
    └── utils_test.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .editorconfig
================================================
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org

root = true


[*]

# Change these settings to your own preference
indent_style = space
indent_size = 4

# We recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false


================================================
FILE: .gitignore
================================================
node_modules
npm-debug.log
tmp


================================================
FILE: .jshintrc
================================================
{
  "curly": true,
  "eqeqeq": true,
  "immed": true,
  "latedef": true,
  "newcap": true,
  "noarg": true,
  "sub": true,
  "undef": true,
  "boss": true,
  "eqnull": true,
  "node": true,
  "es5": true
}


================================================
FILE: .npmignore
================================================


================================================
FILE: Gruntfile.js
================================================
/*
 * grunt-connect-proxy
 * https://github.com/drewzboto/grunt-connect-proxy
 *
 * Copyright (c) 2013 Drewz
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  var proxySnippet = require("./lib/utils.js").proxyRequest;

  // Project configuration.
  grunt.initConfig({
    jshint: {
      all: [
        'Gruntfile.js',
        'tasks/*.js',
        'lib/*.js',
        '<%= nodeunit.tests %>'
      ],
      options: {
        jshintrc: '.jshintrc'
      }
    },

    // Before generating any new files, remove any previously-created files.
    clean: {
      tests: ['tmp']
    },

    // Configuration to be run (and then tested).
    connect: {
      options: {
          port: 9000,
          // change this to '0.0.0.0' to access the server from outside
          hostname: 'localhost'
      },
      proxies:
      [
            {
              context: '/defaults',
              host: 'www.defaults.com'
            },
            {
              context: '/full',
              host: 'www.full.com',
              port: 8080,
              https: true,
              xforward: true,
              rewrite: {
                '^/full': '/anothercontext'
              },
              headers: {
                "X-Proxied-Header": "added"
              },
              ws: true
            },
            {
              context: '/context/test',
              host: 'www.anothercontext.com',
              rewrite: {
                '^/context': '/anothercontext',
                'test': 'testing'
              }
            },
            {
              context: '/invalidrewrite',
              host: 'www.invalidrewrite.com',
              rewrite: {
                '^/undefined': undefined,
                '^/notstring': 13,
                '^/in': '/thisis'
              }
            },
            {
              context: '/missinghost'
            },
            {
              host: 'www.missingcontext.com'
            },
            {
              context: ['/array1','/array2'],
              host: 'www.defaults.com'
            },
            {
              context: '/rewrite',
              host: 'www.yetanothercontext.com',
              rewrite: {
                '^(/)rewrite': function(match, p1) {
                  return p1;
                }
              }
            }
      ],
      server2: {
        proxies: [
          {
            context: '/',
            host: 'www.server2.com'
          }
        ]
      },
      server3: {
        appendProxies: false,
        proxies: [
          {
            context: '/server3',
            host: 'www.server3.com',
            port: 8080,
          }
        ]
      },
      request: {
        options: {
          middleware: function (connect, options) {
            return [require('./lib/utils').proxyRequest];
          }
        },
        proxies: [
          {
            context: '/request',
            host: 'localhost',
            port: 8080,
            headers: {
              "x-proxied-header": "added"
            }
          },
          {
            context: '/hideHeaders',
            host: 'localhost',
            port: 8081,
            hideHeaders: ['x-hidden-header-1', 'X-HiDdEn-HeAdEr-2']
          }
        ]
      }
    },

    // Unit tests.
    nodeunit: {
      tests: 'test/connect_proxy_test.js',
      server2: 'test/server2_proxy_test.js',
      server3: 'test/server3_proxy_test.js',
      utils: 'test/utils_test.js',
      request: 'test/request_test.js',
      hideHeaders: 'test/hide_headers_test.js'
    }

  });

  // Actually load this plugin's task(s).
  grunt.loadTasks('tasks');

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-nodeunit');

  // Whenever the "test" task is run, first clean the "tmp" dir, then run this
  // plugin's task(s), then test the result.
  grunt.registerTask('test', [
    'clean',
    'nodeunit:utils',
    'configureProxies',
    'nodeunit:tests',
    'configureProxies:server2',
    'nodeunit:server2',
    'configureProxies:server3',
    'nodeunit:server3',
    'configureProxies:request',
    'connect:request',
    'nodeunit:request',
    'nodeunit:hideHeaders'
    ]);

  // specifically test that option inheritance works for multi-level config
  grunt.registerTask('test-inheritance', [
    'clean',
    'configureProxies:server2',
    'nodeunit:server2'
  ]);


  // By default, lint and run all tests.
  grunt.registerTask('default', ['jshint', 'test']);

};


================================================
FILE: LICENSE-MIT
================================================
Copyright (c) 2013 Drewz

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.


================================================
FILE: README.md
================================================
# grunt-connect-proxy

> Provides a http proxy as middleware for the grunt-contrib-connect plugin.

## Getting Started
This plugin requires Grunt `~0.4.1`

If 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:

```shell
npm install grunt-connect-proxy --save-dev
```

One the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

```js
grunt.loadNpmTasks('grunt-connect-proxy');
```

## Adapting the  "connect" task

### Overview

#### Proxy Configuration
In your project's Gruntfile, add a section named `proxies` to your existing connect definition.

```js
grunt.initConfig({
    connect: {
        server: {
            options: {
                port: 9000,
                hostname: 'localhost'
            },
            proxies: [
                {
                    context: '/cortex',
                    host: '10.10.2.202',
                    port: 8080,
                    https: false,
                    xforward: false,
                    headers: {
                        "x-custom-added-header": value
                    },
                    hideHeaders: ['x-removed-header']
                }
            ]
        }
    }
})
```
#### Adding the middleware

##### With Livereload

Add the middleware call from the connect option middleware hook
```js
        connect: {
            livereload: {
                options: {
                    middleware: function (connect, options) {
                        if (!Array.isArray(options.base)) {
                            options.base = [options.base];
                        }

                        // Setup the proxy
                        var middlewares = [require('grunt-connect-proxy/lib/utils').proxyRequest];

                        // Serve static files.
                        options.base.forEach(function(base) {
                            middlewares.push(connect.static(base));
                        });

                        // Make directory browse-able.
                        var directory = options.directory || options.base[options.base.length - 1];
                        middlewares.push(connect.directory(directory));

                        return middlewares;
                    }
                }
            }
        }
```

##### Without Livereload

It is possible to add the proxy middleware without Livereload as follows:

```js
   // server
    connect: {
      server: {
        options: {
          port: 8000,
          base: 'public',
          logger: 'dev',
          hostname: 'localhost',
          middleware: function (connect, options, defaultMiddleware) {
             var proxy = require('grunt-connect-proxy/lib/utils').proxyRequest;
             return [
                // Include the proxy first
                proxy
             ].concat(defaultMiddleware);
          }
        },
        proxies: [ /* as defined above */ ]
      }
  }
```

### Adding the configureProxy task to the server task
For the server task, add the configureProxies task before the connect task
```js
    grunt.registerTask('server', function (target) {
        grunt.task.run([
            'clean:server',
            'compass:server',
            'configureProxies:server',
            'livereload-start',
            'connect:livereload',
            'open',
            'watch'
        ]);
    });
```

**IMPORTANT**: You must specify the connect target in the `configureProxies` task.

### Options
The 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

#### options.context
Type: `String` or `Array`

The context(s) to match requests against. Matching requests will be proxied. Should start with /. Should not end with /
Multiple contexts can be matched for the same proxy rule via an array such as:
context: ['/api', '/otherapi']

#### options.host
Type: `String`

The host to proxy to. Should not start with the http/https protocol.

#### options.port
Type: `Number`
Default: 80

The port to proxy to.

#### options.https
Type: `Boolean`
Default: false

 if the proxy should target a https end point on the destination server

#### options.secure
Type: `Boolean`
Default: true

 true/false, if you want to verify the SSL Certs (Avoids: SELF_SIGNED_CERT_IN_CHAIN errors when set to false)

Whether to proxy with https

#### options.xforward:
Type: `Boolean`
Default: false

Whether to add x-forward headers to the proxy request, such as
  "x-forwarded-for": "127.0.0.1",
  "x-forwarded-port": 50892,
  "x-forwarded-proto": "http"


#### options.appendProxies
Type: `Boolean`
Default: true

Set to false to isolate multi-task configuration proxy options from parent level instead of appending them.

#### options.rewrite
Type: `Object`

Allows 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:

```js
proxies: [
    context: '/context',
    host: 'host',
    port: 8080,
    rewrite: {
        '^/removingcontext': '',
        '^/changingcontext': '/anothercontext',
        '^/updating(context)': function(match, p1) {
            return '/new' + p1;
        }
    }
]
```

#### options.headers
Type: `Object`

A map of headers to be added to proxied requests.

#### options.hostRewrite
Type: `String`

Rewrites the location hostname on 30X redirects.

#### options.hideHeaders
Type: `Array`

An array of headers that should be removed from the server's response.

#### options.errorHandler
Type: `Function`

Another middleware that will be called if proxy request fails.
Example:
```js
    errorHandler: function(req, res, next, err) {
        if (err.code === 404) {
            res.send('Some error page');
        } else {
            next();
        }
    }
```

#### options.ws
Type: `Boolean`
Default: false

Set to true to proxy websockets.

## Contributing
In 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/).

#### Multi-server proxy configuration

grunt-contrib-connect multi-server configuration is supported. You can define _proxies_ blocks in per-server options and refer to those blocks in task invocation.

```js
grunt.initConfig({
    connect: {
            options: {
                port: 9000,
                hostname: 'localhost'
            },
            server2: {
                proxies: [
                    {
                        context: '/cortex',
                        host: '10.10.2.202',
                        port: 8080,
                        https: false,
                    }
                ]
            },
            server3: {
                appendProxies: false,
                proxies: [
                    {
                        context: '/api',
                        host: 'example.org'
                    }
                ]
            }
        }
})

grunt.registerTask('e2etest', function (target) {
    grunt.task.run([
        'configureProxies:server2',
        'open',
        'karma'
    ]);
});
```


## Release History
* 0.1.0 Initial release
* 0.1.1 Fix changeOrigin
* 0.1.2 Support multiple server definitions, bumped to grunt 0.4.1 (thanks to @lauripiispanen)
* 0.1.3 Bumped http-proxy dependency to 0.10.2
* 0.1.4 Added proxy rewrite support (thanks to @slawrence)
* 0.1.5 Default rejectUnauthorized to false to allow self-signed certificates over SSL
* 0.1.6 Add xforward option, added support for context arrays, added debug logging
* 0.1.7 Added WebSocket support (thanks for @killfill), Headers support (thanks to @gadr), various docs fixed
* 0.1.8 Minor websocket bug fix
* 0.1.10 Minor bug fix
* 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)
* 0.2.0 Added hidden headers support


================================================
FILE: examples/sample.yeoman.grunt.js
================================================
// Generated on 2013-02-28 using generator-webapp 0.1.5
'use strict';
var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;
var mountFolder = function (connect, dir) {
    return connect.static(require('path').resolve(dir));
};
var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {
    // load all grunt tasks
    require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

    // configurable paths
    var yeomanConfig = {
        app: 'app',
        dist: 'dist'
    };

    grunt.initConfig({
        yeoman: yeomanConfig,
        watch: {
            compass: {
                files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
                tasks: ['compass']
            },
            livereload: {
                files: [
                    '<%= yeoman.app %>/*.html',
                    '{.tmp,<%= yeoman.app %>}/styles/{,*/}*.css',
                    '{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
                    '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,webp}'
                ],
                tasks: ['livereload']
            }
        },
        connect: {
            options: {
                port: 9000,
                // change this to '0.0.0.0' to access the server from outside
                hostname: 'localhost'
            },
            proxies: [
                {
                    context: '/cortex',
                    host: 'localhost',
                    port: 8080
                }
            ],
            livereload: {
                options: {
                    middleware: function (connect) {
                        return [
                            proxySnippet,
                            lrSnippet,
                            mountFolder(connect, '.tmp'),
                            mountFolder(connect, 'app')
                        ];
                    }
                }
            },
            test: {
                options: {
                    middleware: function (connect) {
                        return [
                            mountFolder(connect, '.tmp'),
                            mountFolder(connect, 'test')
                        ];
                    }
                }
            },
            dist: {
                options: {
                    middleware: function (connect) {
                        return [
                            mountFolder(connect, 'dist')
                        ];
                    }
                }
            }
        },
        open: {
            server: {
                path: 'http://localhost:<%= connect.options.port %>'
            }
        },
        clean: {
            dist: ['.tmp', '<%= yeoman.dist %>/*'],
            server: '.tmp'
        },
        jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            all: [
                'Gruntfile.js',
                '<%= yeoman.app %>/scripts/{,*/}*.js',
                '!<%= yeoman.app %>/scripts/vendor/*',
                'test/spec/{,*/}*.js'
            ]
        },
        mocha: {
            all: {
                options: {
                    run: true,
                    urls: ['http://localhost:<%= connect.options.port %>/index.html']
                }
            }
        },
        compass: {
            options: {
                sassDir: '<%= yeoman.app %>/styles',
                cssDir: '.tmp/styles',
                imagesDir: '<%= yeoman.app %>/images',
                javascriptsDir: '<%= yeoman.app %>/scripts',
                fontsDir: '<%= yeoman.app %>/styles/fonts',
                importPath: 'app/components',
                relativeAssets: true
            },
            dist: {},
            server: {
                options: {
                    debugInfo: true
                }
            }
        },
        // not used since Uglify task does concat,
        // but still available if needed
        /*concat: {
            dist: {}
        },*/
        requirejs: {
            dist: {
                // Options: https://github.com/jrburke/r.js/blob/master/build/example.build.js
                options: {
                    // `name` and `out` is set by grunt-usemin
                    baseUrl: 'app/scripts',
                    optimize: 'none',
                    // TODO: Figure out how to make sourcemaps work with grunt-usemin
                    // https://github.com/yeoman/grunt-usemin/issues/30
                    //generateSourceMaps: true,
                    // required to support SourceMaps
                    // http://requirejs.org/docs/errors.html#sourcemapcomments
                    preserveLicenseComments: false,
                    useStrict: true,
                    wrap: true,
                    //uglify2: {} // https://github.com/mishoo/UglifyJS2
                }
            }
        },
        useminPrepare: {
            html: '<%= yeoman.app %>/index.html',
            options: {
                dest: '<%= yeoman.dist %>'
            }
        },
        usemin: {
            html: ['<%= yeoman.dist %>/{,*/}*.html'],
            css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
            options: {
                dirs: ['<%= yeoman.dist %>']
            }
        },
        imagemin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>/images',
                    src: '{,*/}*.{png,jpg,jpeg}',
                    dest: '<%= yeoman.dist %>/images'
                }]
            }
        },
        cssmin: {
            dist: {
                files: {
                    '<%= yeoman.dist %>/styles/main.css': [
                        '.tmp/styles/{,*/}*.css',
                        '<%= yeoman.app %>/styles/{,*/}*.css'
                    ]
                }
            }
        },
        htmlmin: {
            dist: {
                options: {
                    /*removeCommentsFromCDATA: true,
                    // https://github.com/yeoman/grunt-usemin/issues/44
                    //collapseWhitespace: true,
                    collapseBooleanAttributes: true,
                    removeAttributeQuotes: true,
                    removeRedundantAttributes: true,
                    useShortDoctype: true,
                    removeEmptyAttributes: true,
                    removeOptionalTags: true*/
                },
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>',
                    src: '*.html',
                    dest: '<%= yeoman.dist %>'
                }]
            }
        },
        copy: {
            dist: {
                files: [{
                    expand: true,
                    dot: true,
                    cwd: '<%= yeoman.app %>',
                    dest: '<%= yeoman.dist %>',
                    src: [
                        '*.{ico,txt}',
                        '.htaccess'
                    ]
                }]
            }
        },
        bower: {
            all: {
                rjsConfig: '<%= yeoman.app %>/scripts/main.js'
            }
        }
    });

    grunt.renameTask('regarde', 'watch');

    grunt.registerTask('server', function (target) {
        if (target === 'dist') {
            return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
        }

        grunt.task.run([
            'clean:server',
            'compass:server',
            'configureProxies',
            'livereload-start',
            'connect:livereload',
            'open',
            'watch'
        ]);
    });

    grunt.registerTask('test', [
        'clean:server',
        'compass',
        'connect:test',
        'mocha'
    ]);

    grunt.registerTask('build', [
        'clean:dist',
        'compass:dist',
        'useminPrepare',
        'requirejs',
        'imagemin',
        'htmlmin',
        'concat',
        'cssmin',
        'uglify',
        'copy',
        'usemin'
    ]);

    grunt.registerTask('default', [
        'jshint',
        'test',
        'build'
    ]);
};


================================================
FILE: lib/utils.js
================================================
'use strict';
var utils = module.exports;
var httpProxy = require('http-proxy');
var grunt = require('grunt');
var _ = require('lodash');
var proxies = [];
var rewrite = function (req) {
    return function (rule) {
        if (rule.from.test(req.url)) {
            req.url = req.url.replace(rule.from, rule.to);
        }
    };
};

utils.registerProxy = function(proxy) {
    proxies.push(proxy);
};

utils.proxies = function() {
    return proxies;
};

utils.reset = function() {
    proxies = [];
};

utils.validateRewrite = function (rule) {
    if (!rule ||
        typeof rule.from === 'undefined' ||
        typeof rule.to === 'undefined' ||
        typeof rule.from !== 'string' ||
        (typeof rule.to !== 'string' && typeof rule.to !== 'function')) {
        return false;
    }
    return true;
};

utils.processRewrites = function (rewrites) {
    var rules = [];

    Object.keys(rewrites || {}).forEach(function (from) {
        var rule = {
            from: from,
            to: rewrites[from]
        };

        if (utils.validateRewrite(rule)) {
            rule.from = new RegExp(rule.from);
            rules.push(rule);
            grunt.log.writeln('Rewrite rule created for: [' + rule.from + ' -> ' + rule.to + '].');
        } else {
            grunt.log.error('Invalid rule');
        }
    });

    return rules;
};

utils.matchContext = function(context, url) {
    var positiveContexts, negativeContexts, positiveMatch, negativeMatch;
    var contexts = context;
    if (!_.isArray(contexts)) {
        contexts = [contexts];
    }
    positiveContexts = _.filter(contexts, function(c){return c.charAt(0) !== '!';});
    negativeContexts = _.filter(contexts, function(c){return c.charAt(0) === '!';});
    // Remove the '!' character from the contexts
    negativeContexts = _.map(negativeContexts, function(c){return c.slice(1);});
    negativeMatch = _.find(negativeContexts, function(c){return url.lastIndexOf(c, 0) === 0;});
    // If any context negates this url, it must not be proxied.
    if (negativeMatch) {
        return false;
    }
    positiveMatch = _.find(positiveContexts, function(c){return url.lastIndexOf(c, 0) === 0;});
    // If there is any positive match, lets proxy this url.
    return positiveMatch != null;
};

utils.getTargetUrl = function(options){
    var protocol = options.ws ? 'ws' : 'http';
    if(options.https) {
        protocol += 's';
    }

    var target = protocol + '://' + options.host;
    var standardPort = (options.port === 80 && !options.https) || (options.port === 443 && options.https);

    if(!standardPort){
        target += ':' + options.port;
    }
    return target;
};

function onUpgrade(req, socket, head) {
    var proxied = false;

    proxies.forEach(function(proxy) {
        if (!proxied && req && proxy.config.ws && utils.matchContext(proxy.config.context, req.url)) {
            if (proxy.config.rules.length) {
                proxy.config.rules.forEach(rewrite(req));
            }
            proxy.server.ws(req, socket, head);

            proxied = true;

            var source = req.url;
            var target = utils.getTargetUrl(proxy.config) + req.url;
            grunt.log.verbose.writeln('[WS] Proxied request: ' + source + ' -> ' + target + '\n' + JSON.stringify(req.headers, true, 2));
        }
    });
}

//Listen for the update event,onces. grunt-contrib-connect doesnt expose the server object, so bind after the first req
function enableWebsocket(server) {
    if (server && !server.proxyWs) {
        server.proxyWs = true;
        grunt.log.verbose.writeln('[WS] Catching upgrade event...');
        server.on('upgrade', onUpgrade);
    }
}

function removeHiddenHeaders(proxy) {
    var hiddenHeaders = proxy.config.hideHeaders;

    if(hiddenHeaders && hiddenHeaders.length > 0) {
        hiddenHeaders = hiddenHeaders.map(function(header) {
          return header.toLowerCase();
        });

        proxy.server.on('proxyRes', function(proxyRes) {
            var headers = proxyRes.headers;
            hiddenHeaders.forEach(function(header) {
                if(header in headers) {
                    delete headers[header];
                }
            });
        });
    }
}

utils.proxyRequest = function (req, res, next) {
    var proxied = false;

    enableWebsocket(req.connection.server);

    proxies.forEach(function(proxy) {
        if (!proxied && req && utils.matchContext(proxy.config.context, req.url)) {
            if (proxy.config.rules.length) {
                proxy.config.rules.forEach(rewrite(req));
            }
            // Add headers present in the config object
            if (proxy.config.headers != null) {
                _.forOwn(proxy.config.headers, function(value, key) {
                    req.headers[key] = value;
                });
            }

            proxy.server.proxyRequest(req, res, proxy.server, function(err) {
                if (proxy.config.errorHandler) {
                    grunt.log.verbose.writeln('Request failed. Skipping to next midleware.');
                    proxy.config.errorHandler(req, res, next, err);
                }
            });
            removeHiddenHeaders(proxy);

            // proxying twice would cause the writing to a response header that is already sent. Bad config!
            proxied = true;

            var source = req.originalUrl;
            var target = utils.getTargetUrl(proxy.config) + req.url;
            grunt.log.verbose.writeln('Proxied request: ' + source + ' -> ' + target + '\n' + JSON.stringify(req.headers, true, 2));
        }
    });
    if (!proxied) {
        next();
    }
};


================================================
FILE: package.json
================================================
{
  "name": "grunt-connect-proxy",
  "description": "Provides a http proxy as middleware for grunt connect.",
  "version": "0.2.0",
  "homepage": "https://github.com/drewzboto/grunt-connect-proxy",
  "author": {
    "name": "Drewz",
    "email": "drewz@2mod5.com"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/drewzboto/grunt-connect-proxy.git"
  },
  "bugs": {
    "url": "https://github.com/drewzboto/grunt-connect-proxy/issues"
  },
  "licenses": [
    {
      "type": "MIT",
      "url": "https://github.com/drewzboto/grunt-connect-proxy/blob/master/LICENSE-MIT"
    }
  ],
  "main": "Gruntfile.js",
  "engines": {
    "node": ">= 0.10.0"
  },
  "scripts": {
    "test": "grunt test"
  },
  "dependencies": {
    "http-proxy": "~1.11.0",
    "lodash": "~0.9.0"
  },
  "devDependencies": {
    "grunt-contrib-jshint": "~0.1.1",
    "grunt-contrib-clean": "~0.4.0",
    "grunt-contrib-nodeunit": "~0.4.1",
    "grunt": "~0.4.1",
    "grunt-contrib-connect": "~0.5.0"
  },
  "peerDependencies": {
    "grunt": "~0.4.1"
  },
  "keywords": [
    "gruntplugin",
    "proxy",
    "connect",
    "http",
    "grunt"
  ]
}


================================================
FILE: tasks/connect_proxy.js
================================================
/*
 * grunt-connect-proxy
 * https://github.com/drewzboto/grunt-connect-proxy
 *
 * Copyright (c) 2013 Drewz
 * Licensed under the MIT license.
 */

'use strict';
var utils = require('../lib/utils');
var _ = require('lodash');

module.exports = function(grunt) {
  grunt.registerTask('configureProxies', 'Configure any specified connect proxies.', function(config) {
    // setup proxy
    var httpProxy = require('http-proxy');
    var proxyOption;
    var proxyOptions = [];
    var validateProxyConfig = function(proxyOption) {
        if (_.isUndefined(proxyOption.host) || _.isUndefined(proxyOption.context)) {
            grunt.log.error('Proxy missing host or context configuration');
            return false;
        }
        if (proxyOption.https && proxyOption.port === 80) {
            grunt.log.warn('Proxy  for ' + proxyOption.context + ' is using https on port 80. Are you sure this is correct?');
        }
        return true;
    };

    utils.reset();
    utils.log = grunt.log;
    if (config) {
        var connectOptions = grunt.config('connect.'+config) || [];
        if (typeof connectOptions.appendProxies === 'undefined' || connectOptions.appendProxies) {
            proxyOptions = proxyOptions.concat(grunt.config('connect.proxies') || []);
        }
        proxyOptions = proxyOptions.concat(connectOptions.proxies || []);
    } else {
        proxyOptions = proxyOptions.concat(grunt.config('connect.proxies') || []);
    }
    proxyOptions.forEach(function(proxy) {
        proxyOption = _.defaults(proxy,  {
            port: proxy.https ? 443 : 80,
            https: false,
            secure: true,
            xforward: false,
            rules: [],
            errorHandler: function(req, res, next) {  },
            ws: false
        });
        if (validateProxyConfig(proxyOption)) {
            proxyOption.rules = utils.processRewrites(proxyOption.rewrite);
            utils.registerProxy({
                server: httpProxy.createProxyServer({
                    target: utils.getTargetUrl(proxyOption),
                    secure: proxyOption.secure,
                    xfwd: proxyOption.xforward,
                    headers: {
                        host: proxyOption.host
                    },
                    hostRewrite: proxyOption.hostRewrite
                }).on('error', function (err, req, res) {
                    grunt.log.error('Proxy error: ', err.code);
                }),
                config: proxyOption
            });
            grunt.log.writeln('Proxy created for: ' +  proxyOption.context + ' to ' + proxyOption.host + ':' + proxyOption.port);
        }
    });
  });
};


================================================
FILE: test/connect_proxy_test.js
================================================
'use strict';

var grunt = require('grunt');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/
var utils = require("../lib/utils.js");

exports.connect_proxy = {
  setUp: function(done) {
    // setup here if necessary
    done();
  },
  default_options: function(test) {
    test.expect(8);
    var proxies = utils.proxies();

    test.equal(proxies.length, 6, 'should return six valid proxies');
    test.notEqual(proxies[0].server, null, 'server should be configured');
    test.equal(proxies[0].config.context, '/defaults', 'should have context set from config');
    test.equal(proxies[0].config.host, 'www.defaults.com', 'should have host set from config');
    test.equal(proxies[0].config.port, 80, 'should have default port 80');
    test.equal(proxies[0].config.https, false, 'should have default http');
    test.equal(proxies[0].config.xforward, false, 'should have default xforward');
    test.equal(proxies[0].config.ws, false, 'should have default ws to false');

    test.done();
  },
  full_options: function(test) {
    test.expect(11);
    var proxies = utils.proxies();

    test.equal(proxies.length, 6, 'should return five valid proxies');
    test.notEqual(proxies[1].server, null, 'server should be configured');
    test.equal(proxies[1].config.context, '/full', 'should have context set from config');
    test.equal(proxies[1].config.host, 'www.full.com', 'should have host set from config');
    test.equal(proxies[1].config.port, 8080, 'should have port set from config');
    test.equal(proxies[1].config.https, true, 'should have http set from config');
    test.equal(proxies[1].config.xforward, true, 'should have xforward set from config');
    test.equal(proxies[1].config.ws, true, 'should have ws set from config');
    test.deepEqual(proxies[1].config.rewrite, { '^/full': '/anothercontext' }, 'should have rewrite set from config');
    test.equal(proxies[1].config.rules.length, 1, 'rules array should have an item');
    test.deepEqual(proxies[1].config.rules[0], { from: new RegExp('^/full'), to: '/anothercontext'}, 'rules object should be converted to regex');

    test.done();
  },

  two_rewrites: function(test) {
    test.expect(2);
    var config = utils.proxies()[2].config;
    test.equal(config.rules.length, 2, 'rules array should have two items');
    test.deepEqual(config.rewrite, { '^/context': '/anothercontext', 'test': 'testing' }, 'should have rewrite set from config');

    test.done();
  },

  invalid_configs: function(test) {
    test.expect(5);
    var proxies = utils.proxies();

    test.equal(proxies.length, 6, 'should not add the 2 invalid proxies');
    test.notEqual(proxies[0].config.context, '/missinghost', 'should not have context set from config with missing host');
    test.notEqual(proxies[0].config.host, 'www.missingcontext.com', 'should not have host set from config with missing context');
    test.notEqual(proxies[1].config.context, '/missinghost', 'should not have context set from config with missing host');
    test.notEqual(proxies[1].config.host, 'www.missingcontext.com', 'should not have host set from config with missing context');
    test.done();
  },

  invalid_rewrite: function(test) {
    test.expect(3);
    var proxies = utils.proxies();
    test.equal(proxies.length, 6, 'proxies should still be valid');
    test.equal(proxies[3].config.rules.length, 1, 'rules array should have one valid item');
    test.deepEqual(proxies[3].config.rules[0], { from: new RegExp('^/in'), to: '/thisis'}, 'rules object should be converted to regex');

    test.done();
  },

  function_rewrite: function(test) {
    test.expect(1);
    console.log(utils.proxies());
    var proxies = utils.proxies(),
        rules = proxies[5].config.rules[0];
    test.equal('/rewrite'.replace(rules.from, rules.to), '/', 'should execute function when replacing');
    test.done();
  },
};


================================================
FILE: test/hide_headers_test.js
================================================
'use strict';

var utils = require("../lib/utils.js");
var http = require('http');

exports.connect_proxy = {
  setUp: function(done) {
    // setup here if necessary
    done();
  },
  proxied_request: function(test) {
    test.expect(2);
    http.createServer(function (req, res) {
      res.writeHead(200, {
        'x-hidden-header-1': 'this header should be removed',
        'x-hidden-header-2': 'this header should also be removed'
      });
      res.end();
    }).listen(8081);

    http.request({
      host: 'localhost',
      path: '/hideHeaders',
      port: 9000
    }, function(response) {

      test.equal(response.headers['x-hidden-header-1'], undefined, 'hidden header should be hidden');
      test.equal(response.headers['x-hidden-header-2'], undefined, 'header hiding is case insensitive');
      test.done();
    }).end();
  }
};


================================================
FILE: test/request_test.js
================================================
'use strict';

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/
var utils = require("../lib/utils.js");
var http = require('http');

exports.connect_proxy = {
  setUp: function(done) {
    // setup here if necessary
    done();
  },
  proxied_request: function(test) {
    test.expect(2);
    http.createServer(function (req, res) {
      test.equal(req.headers["x-proxied-header"], 'added', 'headers should be added to request');
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.write('request successfully proxied!');
      res.end();
    }).listen(8080);

    http.request({
      host: 'localhost',
      path: '/request',
      port: 9000
    }, function(response) {
      var data = '';
      response.on('data', function (chunk) {
        data += chunk;
      });
      response.on('end', function () {
        test.equal(data, 'request successfully proxied!', 'request should be received');
        test.done();
      });
    }).end();
  }
};


================================================
FILE: test/server2_proxy_test.js
================================================
var utils = require("../lib/utils.js");

exports.server2_proxy_test = {
  setUp: function(done) {
    // setup here if necessary
    done();
  },
  proxy_options_test: function(test) {
    test.expect(10);
    var proxies = utils.proxies();

    test.equal(proxies.length, 7, 'should return seven valid proxies');
    test.notEqual(proxies[0].server, null, 'server should be configured');
    test.equal(proxies[0].config.context, '/defaults', 'should have context set from config');
    test.equal(proxies[0].config.host, 'www.defaults.com', 'should have host set from config');
    test.equal(proxies[6].config.context, '/', 'should have context set from config');
    test.equal(proxies[6].config.host, 'www.server2.com', 'should have host set from config');
    test.equal(proxies[0].config.port, 80, 'should have default port 80');
    test.equal(proxies[0].config.https, false, 'should have default http');
    test.equal(proxies[0].config.ws, false, 'should have default ws to false');
    test.equal(proxies[0].config.rules.length, 0, 'rules array should have zero items');

    test.done();
  }
}


================================================
FILE: test/server3_proxy_test.js
================================================
var utils = require("../lib/utils.js");

exports.server3_proxy_test = {
  setUp: function(done) {
    // setup here if necessary
    done();
  },
  proxy_options_test: function(test) {
    test.expect(8);
    var proxies = utils.proxies();

    test.equal(proxies.length, 1, 'should have just one proxy');
    test.notEqual(proxies[0].server, null, 'server should be configured');
    test.equal(proxies[0].config.context, '/server3', 'should have context set from config');
    test.equal(proxies[0].config.host, 'www.server3.com', 'should have host set from config');
    test.equal(proxies[0].config.port, 8080, 'should have port 8080');
    test.equal(proxies[0].config.https, false, 'should have default http');
    test.equal(proxies[0].config.ws, false, 'should have ws default to false');
    test.equal(proxies[0].config.rules.length, 0, 'rules array should have zero items');

    test.done();
  }
}


================================================
FILE: test/utils_test.js
================================================
var utils = require("../lib/utils.js");

exports.utils_test = {
  setUp: function(done) {
    // setup here if necessary
    done();
  },
  match_context_test: function(test) {
    var singleContext, arrayContext, url, match;
    test.expect(6);

    singleContext = '/api';
    url = '/api/mock?suchrequest=1';
    match = utils.matchContext(singleContext, url);
    test.equal(match, true, 'should match single context with matching start');

    url = '/notapi/mock?suchrequest=1';
    match = utils.matchContext(singleContext, url);
    test.equal(match, false, 'should not match single context with different start');

    arrayContext = ['/api', '/superapi'];
    url = '/superapi/mock?suchrequest=1';
    match = utils.matchContext(arrayContext, url);
    test.equal(match, true, 'should match array context with matching start');

    singleContext = '/api';
    url = '/api/mock/api';
    match = utils.matchContext(singleContext, url);
    test.equal(match, true, 'should match array context with matching start if same pattern is found later');

    arrayContext = ['/api', '/superapi', '!/superapi/not'];
    url = '/superapi/not/mock?suchrequest=1';
    match = utils.matchContext(arrayContext, url);
    test.equal(match, false, 'should not match array context with negative context');

    arrayContext = ['/api', '/superapi', '!/superapi/not'];
    url = '/superapi/yep/mock?suchrequest=1';
    match = utils.matchContext(arrayContext, url);
    test.equal(match, true, 'should match array context with different negative context');

    test.done();
  },

  get_target_url_test: function(test){
    var proxyOptions = {
        host: 'foo.com',
        https: true,
        port: 443,
        ws: false
    };

    test.expect(6);
    test.equal(utils.getTargetUrl(proxyOptions), 'https://foo.com');

    proxyOptions.https = false;
    proxyOptions.port = 80;
    test.equal(utils.getTargetUrl(proxyOptions), 'http://foo.com');

    proxyOptions.ws = true;
    test.equal(utils.getTargetUrl(proxyOptions), 'ws://foo.com');

    proxyOptions.https = true;
    proxyOptions.port = 443
    test.equal(utils.getTargetUrl(proxyOptions), 'wss://foo.com');

    proxyOptions.port = 8080;
    proxyOptions.ws = false;
    proxyOptions.https = false;
    test.equal(utils.getTargetUrl(proxyOptions), 'http://foo.com:8080');

    proxyOptions.port = 445;
    proxyOptions.ws = false;
    proxyOptions.https = true;
    test.equal(utils.getTargetUrl(proxyOptions), 'https://foo.com:445');

    test.done();
  }
};
Download .txt
gitextract_n_5bk1va/

├── .editorconfig
├── .gitignore
├── .jshintrc
├── .npmignore
├── Gruntfile.js
├── LICENSE-MIT
├── README.md
├── examples/
│   └── sample.yeoman.grunt.js
├── lib/
│   └── utils.js
├── package.json
├── tasks/
│   └── connect_proxy.js
└── test/
    ├── connect_proxy_test.js
    ├── hide_headers_test.js
    ├── request_test.js
    ├── server2_proxy_test.js
    ├── server3_proxy_test.js
    └── utils_test.js
Download .txt
SYMBOL INDEX (3 symbols across 1 files)

FILE: lib/utils.js
  function onUpgrade (line 94) | function onUpgrade(req, socket, head) {
  function enableWebsocket (line 114) | function enableWebsocket(server) {
  function removeHiddenHeaders (line 122) | function removeHiddenHeaders(proxy) {
Condensed preview — 17 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (46K chars).
[
  {
    "path": ".editorconfig",
    "chars": 415,
    "preview": "# EditorConfig helps developers define and maintain consistent\n# coding styles between different editors and IDEs\n# edit"
  },
  {
    "path": ".gitignore",
    "chars": 31,
    "preview": "node_modules\nnpm-debug.log\ntmp\n"
  },
  {
    "path": ".jshintrc",
    "chars": 206,
    "preview": "{\n  \"curly\": true,\n  \"eqeqeq\": true,\n  \"immed\": true,\n  \"latedef\": true,\n  \"newcap\": true,\n  \"noarg\": true,\n  \"sub\": tru"
  },
  {
    "path": ".npmignore",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "Gruntfile.js",
    "chars": 4665,
    "preview": "/*\n * grunt-connect-proxy\n * https://github.com/drewzboto/grunt-connect-proxy\n *\n * Copyright (c) 2013 Drewz\n * Licensed"
  },
  {
    "path": "LICENSE-MIT",
    "chars": 1049,
    "preview": "Copyright (c) 2013 Drewz\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software "
  },
  {
    "path": "README.md",
    "chars": 8386,
    "preview": "# grunt-connect-proxy\n\n> Provides a http proxy as middleware for the grunt-contrib-connect plugin.\n\n## Getting Started\nT"
  },
  {
    "path": "examples/sample.yeoman.grunt.js",
    "chars": 8368,
    "preview": "// Generated on 2013-02-28 using generator-webapp 0.1.5\n'use strict';\nvar lrSnippet = require('grunt-contrib-livereload/"
  },
  {
    "path": "lib/utils.js",
    "chars": 5643,
    "preview": "'use strict';\nvar utils = module.exports;\nvar httpProxy = require('http-proxy');\nvar grunt = require('grunt');\nvar _ = r"
  },
  {
    "path": "package.json",
    "chars": 1143,
    "preview": "{\n  \"name\": \"grunt-connect-proxy\",\n  \"description\": \"Provides a http proxy as middleware for grunt connect.\",\n  \"version"
  },
  {
    "path": "tasks/connect_proxy.js",
    "chars": 2659,
    "preview": "/*\n * grunt-connect-proxy\n * https://github.com/drewzboto/grunt-connect-proxy\n *\n * Copyright (c) 2013 Drewz\n * Licensed"
  },
  {
    "path": "test/connect_proxy_test.js",
    "chars": 4436,
    "preview": "'use strict';\n\nvar grunt = require('grunt');\n\n/*\n  ======== A Handy Little Nodeunit Reference ========\n  https://github."
  },
  {
    "path": "test/hide_headers_test.js",
    "chars": 853,
    "preview": "'use strict';\n\nvar utils = require(\"../lib/utils.js\");\nvar http = require('http');\n\nexports.connect_proxy = {\n  setUp: f"
  },
  {
    "path": "test/request_test.js",
    "chars": 1542,
    "preview": "'use strict';\n\n/*\n  ======== A Handy Little Nodeunit Reference ========\n  https://github.com/caolan/nodeunit\n\n  Test met"
  },
  {
    "path": "test/server2_proxy_test.js",
    "chars": 1106,
    "preview": "var utils = require(\"../lib/utils.js\");\n\nexports.server2_proxy_test = {\n  setUp: function(done) {\n    // setup here if n"
  },
  {
    "path": "test/server3_proxy_test.js",
    "chars": 910,
    "preview": "var utils = require(\"../lib/utils.js\");\n\nexports.server3_proxy_test = {\n  setUp: function(done) {\n    // setup here if n"
  },
  {
    "path": "test/utils_test.js",
    "chars": 2521,
    "preview": "var utils = require(\"../lib/utils.js\");\n\nexports.utils_test = {\n  setUp: function(done) {\n    // setup here if necessary"
  }
]

About this extraction

This page contains the full source code of the drewzboto/grunt-connect-proxy GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 17 files (42.9 KB), approximately 10.5k tokens, and a symbol index with 3 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!