adding grunt and grunt-contrib-connect

master
Matt Huntington 12 years ago
parent ad06b405b7
commit 1058e48b51

@ -0,0 +1,22 @@
Copyright (c) 2014 "Cowboy" Ben Alman, contributors
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.

@ -0,0 +1,355 @@
# grunt-contrib-connect v0.8.0 [![Build Status: Linux](https://travis-ci.org/gruntjs/grunt-contrib-connect.png?branch=master)](https://travis-ci.org/gruntjs/grunt-contrib-connect)
> Start a connect web server.
## Getting Started
This plugin requires Grunt `~0.4.0`
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-contrib-connect --save-dev
```
Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:
```js
grunt.loadNpmTasks('grunt-contrib-connect');
```
## Connect task
_Run this task with the `grunt connect` command._
Note that this server only runs as long as grunt is running. Once grunt's tasks have completed, the web server stops. This behavior can be changed with the [keepalive](#keepalive) option, and can be enabled ad-hoc by running the task like `grunt connect:keepalive`.
This task was designed to be used in conjunction with another task that is run immediately afterwards, like the [grunt-contrib-qunit plugin](https://github.com/gruntjs/grunt-contrib-qunit) `qunit` task.
### Options
#### port
Type: `Integer`
Default: `8000`
The port on which the webserver will respond. The task will fail if the specified port is already in use. You can use the special values `0` or `'?'` to use a system-assigned port.
#### protocol
Type: `String`
Default: `'http'`
May be `'http'` or `'https'`.
#### hostname
Type: `String`
Default: `'0.0.0.0'`
The hostname the webserver will use.
Setting it to `'*'` will make the server accessible from anywhere.
#### base
Type: `String` or `Array`
Default: `'.'`
The base (or root) directory from which files will be served. Defaults to the project Gruntfile's directory.
Can be an array of bases to serve multiple directories. The last base given will be the directory to become browse-able.
#### directory
Type: `String`
Default: `null`
Set to the directory you wish to be browse-able. Used to override the `base` option browse-able directory.
#### keepalive
Type: `Boolean`
Default: `false`
Keep the server alive indefinitely. Note that if this option is enabled, any tasks specified after this task will _never run_. By default, once grunt's tasks have completed, the web server stops. This option changes that behavior.
This option can also be enabled ad-hoc by running the task like `grunt connect:targetname:keepalive`
#### debug
Type: `Boolean`
Default: `false`
Set the `debug` option to true to enable logging instead of using the `--debug` flag.
#### livereload
Type: `Boolean` or `Number`
Default: `false`
Set to `true` or a port number to inject a live reload script tag into your page using [connect-livereload](https://github.com/intesso/connect-livereload).
*This does not perform live reloading. It is intended to be used in tandem with grunt-contrib-watch or another task that will trigger a live reload server upon files changing.*
#### open
Type: `Boolean` or `String` or `Object`
Default: `false`
Open the served page in your default browser. Specifying `true` opens the default server URL, specifying a URL opens that URL or specify an object with the following keys to configure open directly (each are optional):
```js
{
target: 'http://localhost:8000', // target url to open
appName: 'open', // name of the app that opens, ie: open, start, xdg-open
callback: function() {} // called when the app has opened
}
```
#### useAvailablePort
Type: `Boolean`
Default: `false`
If `true` the task will look for the next available port after the set `port` option.
#### onCreateServer
Type: `Function` or `Array`
Default: `null`
A function to be called after the server object is created, to allow integrating libraries that need access to connect's server object. A Socket.IO example:
```js
grunt.initConfig({
connect: {
server: {
options: {
port: 8000,
hostname: '*',
onCreateServer: function(server, connect, options) {
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket) {
// do something with socket
});
}
}
}
}
});
```
#### middleware
Type: `Function` or `Array`
Default: `Array` of connect middlewares that use `options.base` for static files and directory browsing
As an `Array`:
```js
grunt.initConfig({
connect: {
server: {
options: {
middleware: [
function myMiddleware(req, res, next) {
res.end('Hello, world!');
}
],
},
},
},
});
```
As a `function`:
```js
grunt.initConfig({
connect: {
server: {
options: {
middleware: function(connect, options, middlewares) {
// inject a custom middleware into the array of default middlewares
middlewares.push(function(req, res, next) {
if (req.url !== '/hello/world') return next();
res.end('Hello, world from port #' + options.port + '!');
});
return middlewares;
},
},
},
},
});
```
Lets you add in your own Connect middlewares. This option expects a function that returns an array of middlewares. See the [project Gruntfile][] and [project unit tests][] for a usage example.
[project Gruntfile]: Gruntfile.js
[project unit tests]: test/connect_test.js
### Usage examples
#### Basic Use
In this example, `grunt connect` (or more verbosely, `grunt connect:server`) will start a static web server at `http://localhost:9001/`, with its base path set to the `www-root` directory relative to the gruntfile, and any tasks run afterwards will be able to access it.
```javascript
// Project configuration.
grunt.initConfig({
connect: {
server: {
options: {
port: 9001,
base: 'www-root'
}
}
}
});
```
If you want your web server to use the default options, just omit the `options` object. You still need to specify a target (`uses_defaults` in this example), but the target's configuration object can otherwise be empty or nonexistent. In this example, `grunt connect` (or more verbosely, `grunt connect:uses_defaults`) will start a static web server using the default options.
```javascript
// Project configuration.
grunt.initConfig({
connect: {
uses_defaults: {}
}
});
```
#### Multiple Servers
You can specify multiple servers to be run alone or simultaneously by creating a target for each server. In this example, running either `grunt connect:site1` or `grunt connect:site2` will start the appropriate web server, but running `grunt connect` will run _both_. Note that any server for which the [keepalive](#keepalive) option is specified will prevent _any_ task or target from running after it.
```javascript
// Project configuration.
grunt.initConfig({
connect: {
site1: {
options: {
port: 9000,
base: 'www-roots/site1'
}
},
site2: {
options: {
port: 9001,
base: 'www-roots/site2'
}
}
}
});
```
#### Roll Your Own
Like the [Basic Use](#basic-use) example, this example will start a static web server at `http://localhost:9001/`, with its base path set to the `www-root` directory relative to the gruntfile. Unlike the other example, this is done by creating a brand new task. in fact, this plugin isn't even installed!
```javascript
// Project configuration.
grunt.initConfig({ /* Nothing needed here! */ });
// After running "npm install connect --save-dev" to add connect as a dev
// dependency of your project, you can require it in your gruntfile with:
var connect = require('connect');
// Now you can define a "connect" task that starts a webserver, using the
// connect lib, with whatever options and configuration you need:
grunt.registerTask('connect', 'Start a custom static web server.', function() {
grunt.log.writeln('Starting static web server in "www-root" on port 9001.');
connect(connect.static('www-root')).listen(9001);
});
```
#### Support for HTTPS
A default certificate authority, certificate and key file are provided and pre-
configured for use when `protocol` has been set to `https`.
NOTE: No passphrase set for the certificate.
If you are getting warnings in Google Chrome, add 'server.crt' (from 'node_modules/tasks/certs')
to your keychain.
In OS X, after you add 'server.crt', right click on the certificate,
select 'Get Info' - 'Trust' - 'Always Trust', close window, restart Chrome.
###### Advanced HTTPS config
If the default certificate setup is unsuitable for your environment, OpenSSL
can be used to create a set of self-signed certificates with a local ca root.
```shell
### Create ca.key, use a password phrase when asked
### When asked 'Common Name (e.g. server FQDN or YOUR name) []:' use your hostname, i.e 'mysite.dev'
openssl genrsa -des3 -out ca.key 1024
openssl req -new -key ca.key -out ca.csr
openssl x509 -req -days 365 -in ca.csr -out ca.crt -signkey ca.key
### Create server certificate
openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr
### Remove password from the certificate
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
### Generate self-siged certificate
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
```
For more details on the various options that can be set when configuring SSL,
please see the Node documentation for [TLS][].
Grunt configuration would become
```javascript
// Project configuration.
grunt.initConfig({
connect: {
server: {
options: {
protocol: 'https',
port: 8443,
key: grunt.file.read('server.key').toString(),
cert: grunt.file.read('server.crt').toString(),
ca: grunt.file.read('ca.crt').toString()
},
},
},
});
```
[TLS]: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
#### Grunt Events
The connect plugin will emit a grunt event, `connect.{taskName}.listening`, once the server has started. You can listen for this event to run things against a keepalive server, for example:
```javascript
grunt.registerTask('jasmine-server', 'start web server for jasmine tests in browser', function() {
grunt.task.run('jasmine:tests:build');
grunt.event.once('connect.tests.listening', function(host, port) {
var specRunnerUrl = 'http://' + host + ':' + port + '/_SpecRunner.html';
grunt.log.writeln('Jasmine specs available at: ' + specRunnerUrl);
require('open')(specRunnerUrl);
});
grunt.task.run('connect:tests:keepalive');
});
```
## Release History
* 2014-06-09v0.8.0Update connect and connect-livereload.
* 2014-02-27v0.7.1Fixes issue with the '*' hostname option.
* 2014-02-18v0.7.0Update connect to ~2.13.0. Default hostname switched to '0.0.0.0'. Modified options.middleware to accept an array or a function.
* 2013-12-29v0.6.0Open options.hostname if provided. Update connect-livereload to ~0.3.0. Update connect to ~2.12.0. Use well-formed ssl certificates. Support all options of open. Make directory browseable when base is a string.
* 2013-09-05v0.5.0Add 'open' option.
* 2013-09-05v0.4.2Un-normalize options.base as it should be a string or an array as the user has set. Fix setting target hostname option.
* 2013-09-02v0.4.1Browse-able directory is the last item supplied to bases. Added directory option to override browse-able directory.
* 2013-09-01v0.4.0Fix logging of which server address. Ability to set multiple bases. Event emitted when server starts listening. Support for HTTPS. debug option added to display debug logging like the --debug flag. livereload option added to inject a livereload snippet into the page.
* 2013-04-10v0.3.0Add ability to listen on system-assigned port.
* 2013-03-07v0.2.0Upgrade connect dependency.
* 2013-02-17v0.1.2Ensure Gruntfile.js is included on npm.
* 2013-02-15v0.1.1First official release for Grunt 0.4.0.
* 2013-01-18v0.1.1rc6Updating grunt/gruntplugin dependencies to rc6. Changing in-development grunt/gruntplugin dependency versions from tilde version ranges to specific versions.
* 2013-01-09v0.1.1rc5Updating to work with grunt v0.4.0rc5.
* 2012-11-01v0.1.0Work in progress, not yet officially released.
---
Task submitted by ["Cowboy" Ben Alman](http://benalman.com)
*This file was generated on Mon Jun 09 2014 14:17:55.*

@ -0,0 +1,3 @@
language: node_js
node_js:
- "0.10"

@ -0,0 +1,19 @@
Copyright (c) 2010-2014 Caolan McMahon
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 diff suppressed because it is too large Load Diff

@ -0,0 +1,11 @@
{
"name": "async",
"repo": "caolan/async",
"description": "Higher-order functions and common patterns for asynchronous code",
"version": "0.1.23",
"keywords": [],
"dependencies": {},
"development": {},
"main": "lib/async.js",
"scripts": [ "lib/async.js" ]
}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

@ -0,0 +1,5 @@
examples/
docs/
src/
test/
spec/

@ -0,0 +1,15 @@
language: node_js
node_js:
- "0.11"
- "0.10"
- "0.9"
before_script:
- "npm install"
script:
- "node_modules/mocha/bin/mocha"
notifications:
email: andi.neck@intesso.com

@ -0,0 +1,19 @@
Copyright (c) 2013 intesso
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.

@ -0,0 +1,142 @@
connect-livereload
==================
connect middleware for adding the livereload script to the response.
no browser plugin is needed.
if you are happy with a browser plugin, then you don't need this middleware.
[![Build Status](https://travis-ci.org/intesso/connect-livereload.png)](https://travis-ci.org/intesso/connect-livereload)
[![NPM version](https://badge.fury.io/js/connect-livereload.png)](http://badge.fury.io/js/connect-livereload)
install
=======
```bash
npm install connect-livereload --save-dev
```
use
===
note: if you use this middleware, you should make sure to switch off the Browser LiveReload Extension if you have it installed.
this middleware can be used with a LiveReload server e.g. [grunt-reload](https://github.com/webxl/grunt-reload) or [grunt-contrib-watch](https://github.com/gruntjs/grunt-contrib-watch).
`connect-livereload` itself does not serve the `livereload.js` script.
In your connect or express application add this after the static and before the dynamic routes.
If you need liveReload on static html files, then place it before the static routes.
`ignore` gives you the possibility to ignore certain files or url's from being handled by `connect-livereload`.
## connect/express example
```javascript
app.use(require('connect-livereload')({
port: 35729
}));
```
please see the [examples](https://github.com/intesso/connect-livereload/tree/master/examples) for the app and Grunt configuration.
## options
Options are not mandatory: `app.use(require('connect-livereload')());`
The Options have to be provided when the middleware is loaded:
e.g.:
```
app.use(require('connect-livereload')({
port: 35729,
ignore: ['.js', '.svg']
}));
```
These are the available options with the following defaults:
```javascript
// `ignore` and `include`: array with strings and regex expressions elements.
// strings: included/ignored when the url contains this string
// regex: any expression: e.g. starts with pattern: /^.../ ends with pattern: /...$/
ignore: [/\.js$/, /\.css$/, /\.svg$/, /\.ico$/, /\.woff$/, /\.png$/, /\.jpg$/, /\.jpeg$/],
// include all urls by default
include: [/.*/],
// this function is used to determine if the content of `res.write` or `res.end` is html.
html: function (str) {
return /<[:_-\w\s\!\/\=\"\']+>/i.test(str);
},
// rules are provided to find the place where the snippet should be inserted.
// the main problem is that on the server side it can be tricky to determine if a string will be valid html on the client.
// the function `fn` of the first `match` is executed like this `body.replace(rule.match, rule.fn);`
// the function `fn` has got the arguments `fn(w, s)` where `w` is the matches string and `s` is the snippet.
rules: [{
match: /<\/body>(?![\s\S]*<\/body>)/,
fn: prepend
}, {
match: /<\/html>(?![\s\S]*<\/html>)/,
fn: prepend
}, {
match: /<\!DOCTYPE.+>/,
fn: append
}],
// port where the script is loaded
port: 35729,
// location where the script is provided (not by connect-livereload). Change this e.g. when serving livereload with a proxy.
src: "http://localhost:35729/livereload.js?snipver=1",
```
please see the [examples](https://github.com/intesso/connect-livereload/tree/master/examples) for the app and Grunt configuration.
## grunt example
The following example is from an actual Gruntfile that uses [grunt-contrib-connect](https://github.com/gruntjs/grunt-contrib-connect)
```javascript
connect: {
options: {
port: 3000,
hostname: 'localhost'
},
dev: {
options: {
middleware: function (connect) {
return [
require('connect-livereload')(), // <--- here
checkForDownload,
mountFolder(connect, '.tmp'),
mountFolder(connect, 'app')
];
}
}
}
}
```
For use as middleware in grunt simply add the following to the **top** of your array of middleware.
```javascript
require('connect-livereload')(),
```
You can pass in options to this call if you do not want the defaults.
`dev` is simply the name of the server being used with the task `grunt connect:dev`. The other items in the `middleware` array are all functions that either are of the form `function (req, res, next)` like `checkForDownload` or return that like `mountFolder(connect, 'something')`.
alternative
===========
An alternative would be to install the [LiveReload browser plugin](https://chrome.google.com/webstore/detail/livereload/jnihajbhpnppcggbcgedagnkighmdlei).
credits
=======
* The initial middleware code was mainly extracted from: [grunt-contrib-livereload/util.js](https://github.com/gruntjs/grunt-contrib-livereload/blob/master/lib/utils.js)
* [LiveReload Creator](http://livereload.com/)
tests
=====
run the tests with
```
mocha
```
license
=======
[MIT License](https://github.com/intesso/connect-livereload/blob/master/LICENSE)

@ -0,0 +1,147 @@
module.exports = function livereload(opt) {
// options
var opt = opt || {};
var ignore = opt.ignore || opt.excludeList || [/\.js$/, /\.css$/, /\.svg$/, /\.ico$/, /\.woff$/, /\.png$/, /\.jpg$/, /\.jpeg$/];
var include = opt.include || [/.*/];
var html = opt.html || _html;
var rules = opt.rules || [{
match: /<\/body>(?![\s\S]*<\/body>)/,
fn: prepend
}, {
match: /<\/html>(?![\s\S]*<\/html>)/,
fn: prepend
}, {
match: /<\!DOCTYPE.+>/,
fn: append
}];
var port = opt.port || 35729;
var src = opt.src || "' + (location.protocol || 'http:') + '//' + (location.hostname || 'localhost') + ':" + port + "/livereload.js?snipver=1";
var snippet = "\n<script type=\"text/javascript\">//<![CDATA[\ndocument.write('<script src=\"" + src + "\" type=\"text/javascript\"><\\/script>')\n//]]></script>\n";
// helper functions
var regex = (function() {
var matches = rules.map(function(item) {
return item.match.source;
}).join('|');
return new RegExp(matches);
})();
function prepend(w, s) {
return s + w;
}
function append(w, s) {
return w + s;
}
function _html(str) {
if (!str) return false;
return /<[:_-\w\s\!\/\=\"\']+>/i.test(str);
}
function exists(body) {
if (!body) return false;
return regex.test(body);
}
function snip(body) {
if (!body) return false;
return (~body.lastIndexOf("/livereload.js"));
}
function snap(body) {
var _body = body;
rules.some(function(rule) {
if (rule.match.test(body)) {
_body = body.replace(rule.match, function(w) {
return rule.fn(w, snippet);
});
return true;
}
return false;
});
return _body;
}
function accept(req) {
var ha = req.headers["accept"];
if (!ha) return false;
return (~ha.indexOf("html"));
}
function check(str, arr) {
if (!str) return true;
return arr.some(function(item) {
if ( (item.test && item.test(str) ) || ~str.indexOf(item)) return true;
return false;
});
}
// middleware
return function livereload(req, res, next) {
if (res._livereload) return next();
res._livereload = true;
var writeHead = res.writeHead;
var write = res.write;
var end = res.end;
if (!accept(req) || !check(req.url, include) || check(req.url, ignore)) {
return next();
}
function restore() {
res.writeHead = writeHead;
res.write = write;
res.end = end;
}
res.push = function(chunk) {
res.data = (res.data || '') + chunk;
};
res.inject = res.write = function(string, encoding) {
if (string !== undefined) {
var body = string instanceof Buffer ? string.toString(encoding) : string;
if (exists(body) && !snip(res.data)) {
res.push(snap(body));
return true;
} else if (html(body) || html(res.data)) {
res.push(body);
return true;
} else {
restore();
return write.call(res, string, encoding);
}
}
return true;
};
res.writeHead = function() {
var headers = arguments[arguments.length - 1];
if (headers && typeof headers === 'object') {
for (var name in headers) {
if (/content-length/i.test(name)) {
delete headers[name];
}
}
}
var header = res.getHeader( 'content-length' );
if ( header ) res.removeHeader( 'content-length' );
writeHead.apply(res, arguments);
};
res.end = function(string, encoding) {
restore();
var result = res.inject(string, encoding);
if (!result) return end.call(res, string, encoding);
if (res.data !== undefined && !res._header) res.setHeader('content-length', Buffer.byteLength(res.data, encoding));
res.end(res.data, encoding);
};
next();
};
}

File diff suppressed because one or more lines are too long

@ -0,0 +1,4 @@
coverage/
docs/
test/
.travis.yml

File diff suppressed because it is too large Load Diff

@ -0,0 +1,24 @@
(The MIT License)
Copyright (c) 2010 Sencha Inc.
Copyright (c) 2011 LearnBoost
Copyright (c) 2011 TJ Holowaychuk
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.

@ -0,0 +1,88 @@
# Connect
[![NPM version](https://badge.fury.io/js/connect.svg)](http://badge.fury.io/js/connect)
[![Build Status](https://travis-ci.org/senchalabs/connect.svg?branch=master)](https://travis-ci.org/senchalabs/connect)
[![Coverage Status](https://img.shields.io/coveralls/senchalabs/connect.svg?branch=master)](https://coveralls.io/r/senchalabs/connect)
Connect is an extensible HTTP server framework for [node](http://nodejs.org), providing high performance "plugins" known as _middleware_.
Connect is bundled with over _20_ commonly used middleware, including
a logger, session support, cookie parser, and [more](http://senchalabs.github.com/connect). Be sure to view the 2.x [documentation](http://www.senchalabs.org/connect/).
```js
var connect = require('connect')
, http = require('http');
var app = connect()
.use(connect.favicon('public/favicon.ico'))
.use(connect.logger('dev'))
.use(connect.static('public'))
.use(connect.directory('public'))
.use(connect.cookieParser())
.use(connect.session({ secret: 'my secret here' }))
.use(function(req, res){
res.end('Hello from Connect!\n');
});
http.createServer(app).listen(3000);
```
## Middleware
- [basicAuth](http://www.senchalabs.org/connect/basicAuth.html)
- [bodyParser](http://www.senchalabs.org/connect/bodyParser.html)
- [compress](http://www.senchalabs.org/connect/compress.html)
- [cookieParser](http://www.senchalabs.org/connect/cookieParser.html)
- [cookieSession](http://www.senchalabs.org/connect/cookieSession.html)
- [csrf](http://www.senchalabs.org/connect/csrf.html)
- [directory](http://www.senchalabs.org/connect/directory.html)
- [errorHandler](http://www.senchalabs.org/connect/errorHandler.html)
- [favicon](http://www.senchalabs.org/connect/favicon.html)
- [json](http://www.senchalabs.org/connect/json.html)
- [limit](http://www.senchalabs.org/connect/limit.html)
- [logger](http://www.senchalabs.org/connect/logger.html)
- [methodOverride](http://www.senchalabs.org/connect/methodOverride.html)
- [multipart](http://www.senchalabs.org/connect/multipart.html)
- [urlencoded](http://www.senchalabs.org/connect/urlencoded.html)
- [query](http://www.senchalabs.org/connect/query.html)
- [responseTime](http://www.senchalabs.org/connect/responseTime.html)
- [session](http://www.senchalabs.org/connect/session.html)
- [static](http://www.senchalabs.org/connect/static.html)
- [staticCache](http://www.senchalabs.org/connect/staticCache.html)
- [subdomains](http://www.senchalabs.org/connect/subdomains.html)
- [vhost](http://www.senchalabs.org/connect/vhost.html)
## Running Tests
first:
$ npm install -d
then:
$ npm test
## Contributors
https://github.com/senchalabs/connect/graphs/contributors
## Node Compatibility
Connect `< 1.x` is compatible with node 0.2.x
Connect `1.x` is compatible with node 0.4.x
Connect `2.x` is compatible with node 0.6.x
Connect (_master_) is compatible with node 0.8.x
## CLA
[http://sencha.com/cla](http://sencha.com/cla)
## License
View the [LICENSE](https://github.com/senchalabs/connect/blob/master/LICENSE) file.

@ -0,0 +1,35 @@
/**
* Module dependencies.
*/
var connect = require('../');
function auth(user, pass) {
return 'tj' == user && 'tobi' == pass;
}
function authorized(req, res) {
res.end('authorized!');
}
function hello(req, res) {
res.end('hello! try /admin');
}
// apply globally
connect(
connect.basicAuth(auth)
, authorized
).listen(3000);
// apply to /admin/* only
var server = connect();
server.use('/admin', connect.basicAuth(auth));
server.use('/admin', authorized);
server.use(hello);
server.listen(3001);

@ -0,0 +1,40 @@
var connect = require('../')
, http = require('http');
// visit form.html
var app = connect()
.use(connect.static(__dirname + '/public'))
.use(connect.bodyParser())
.use(form)
.use(upload);
function form(req, res, next){
if ('GET' != req.method) return next();
res.statusCode = 302;
res.setHeader('Location', 'form.html');
res.end();
}
function upload(req, res){
res.setHeader('Content-Type', 'text/html');
res.write('<p>thanks ' + req.body.name + '</p>');
res.write('<ul>');
if (Array.isArray(req.files.images)) {
req.files.images.forEach(function(image){
var kb = image.size / 1024 | 0;
res.write('<li>uploaded ' + image.name + ' ' + kb + 'kb</li>');
});
} else {
var image = req.files.images;
var kb = image.size / 1024 | 0;
res.write('<li>uploaded ' + image.name + ' ' + kb + 'kb</li>');
}
res.end('</ul>');
}
http.Server(app).listen(3000);
console.log('Server started on port 3000');

@ -0,0 +1,41 @@
var connect = require('../')
, http = require('http');
var app = connect()
.use(connect.logger('dev'))
.use(connect.bodyParser())
.use(connect.cookieParser())
.use(connect.cookieSession({ secret: 'some secret' }))
.use(post)
.use(clear)
.use(counter);
function clear(req, res, next) {
if ('/clear' != req.url) return next();
req.session = null;
res.statusCode = 302;
res.setHeader('Location', '/');
res.end();
}
function post(req, res, next) {
if ('POST' != req.method) return next();
req.session.name = req.body.name;
next();
}
function counter(req, res) {
req.session.count = req.session.count || 0;
var n = req.session.count++;
var name = req.session.name || 'Enter your name';
res.end('<p>hits: ' + n + '</p>'
+ '<form method="post">'
+ '<p><input type="text" name="name" value="' + name + '" />'
+ '<input type="submit" value="Save" /></p>'
+ '</form>'
+ '<p><a href="/clear">clear session</a></p>');
}
http.createServer(app).listen(3000);
console.log('Server listening on port 3000');

@ -0,0 +1,36 @@
/**
* Module dependencies.
*/
var connect = require('../')
, http = require('http');
var form = '\n\
<form action="/" method="post">\n\
<input type="hidden" name="_csrf" value="{token}" />\n\
<input type="text" name="user[name]" value="{user}" placeholder="Username" />\n\
<input type="submit" value="Login" />\n\
</form>\n\
';
var app = connect()
.use(connect.cookieParser())
.use(connect.session({ secret: 'keyboard cat' }))
.use(connect.bodyParser())
.use(connect.csrf())
.use(function(req, res, next){
if ('POST' != req.method) return next();
req.session.user = req.body.user;
next();
})
.use(function(req, res){
res.setHeader('Content-Type', 'text/html');
var body = form
.replace('{token}', req.csrfToken())
.replace('{user}', req.session.user && req.session.user.name || '');
res.end(body);
});
http.createServer(app).listen(3000);
console.log('Server listening on port 3000');

@ -0,0 +1,12 @@
/**
* Module dependencies.
*/
var connect = require('../');
var app = connect();
var path = __dirname + '/../';
app.use(connect.directory(path, { icons: true }))
app.use(connect.static(path))
app.listen(3000);

@ -0,0 +1,19 @@
var connect = require('../')
, http = require('http');
// try:
// - viewing in a browser
// - curl http://localhost:3000
// - curl -H "Accept: application/json" http://localhost:3000
var app = connect()
.use(function(req, res, next){
var err = new Error('oh noes!');
err.number = 7;
throw err;
})
.use(connect.errorHandler());
http.Server(app).listen(3000);
console.log('Server started on port 3000');

@ -0,0 +1,12 @@
/**
* Module dependencies.
*/
var connect = require('../');
// $ curl -i http://localhost:3000/favicon.ico
connect.createServer(
connect.favicon()
).listen(3000);

@ -0,0 +1,12 @@
/**
* Module dependencies.
*/
var connect = require('../');
connect.createServer(function(req, res){
var body = 'Hello World';
res.setHeader('Content-Length', body.length);
res.end(body);
}).listen(3000);

@ -0,0 +1,41 @@
var connect = require('../')
, http = require('http');
// visit form.html
var app = connect()
.use(connect.static(__dirname + '/public'))
.use(connect.limit('5mb'))
.use(connect.bodyParser())
.use(form)
.use(upload);
function form(req, res, next){
if ('GET' != req.method) return next();
res.statusCode = 302;
res.setHeader('Location', 'form.html');
res.end();
}
function upload(req, res){
res.setHeader('Content-Type', 'text/html');
res.write('<p>thanks ' + req.body.name + '</p>');
res.write('<ul>');
if (Array.isArray(req.files.images)) {
req.files.images.forEach(function(image){
var kb = image.size / 1024 | 0;
res.write('<li>uploaded ' + image.name + ' ' + kb + 'kb</li>');
});
} else {
var image = req.files.images;
var kb = image.size / 1024 | 0;
res.write('<li>uploaded ' + image.name + ' ' + kb + 'kb</li>');
}
res.end('</ul>');
}
http.Server(app).listen(3000);
console.log('Server started on port 3000');

@ -0,0 +1,14 @@
/**
* Module dependencies.
*/
var connect = require('../');
// $ curl -i http://localhost:3000/favicon.ico
// true defaults to 1000ms
connect.createServer(
connect.logger({ buffer: 5000 })
, connect.favicon()
).listen(3000);

@ -0,0 +1,62 @@
/**
* Module dependencies.
*/
var connect = require('../');
// $ curl http://localhost:3000/
// custom format string
connect.createServer(
connect.logger(':method :url - :res[content-type]')
, function(req, res){
res.statusCode = 500;
res.setHeader('Content-Type', 'text/plain');
res.end('Internal Server Error');
}
).listen(3000);
// $ curl http://localhost:3001/
// $ curl http://localhost:3001/302
// $ curl http://localhost:3001/404
// $ curl http://localhost:3001/500
connect()
.use(connect.logger('dev'))
.use('/connect', connect.static(__dirname + '/lib'))
.use('/connect', connect.directory(__dirname + '/lib'))
.use(function(req, res, next){
switch (req.url) {
case '/500':
var body = 'Internal Server Error';
res.statusCode = 500;
res.setHeader('Content-Length', body.length);
res.end(body);
break;
case '/404':
var body = 'Not Found';
res.statusCode = 404;
res.setHeader('Content-Length', body.length);
res.end(body);
break;
case '/302':
var body = 'Found';
res.statusCode = 302;
res.setHeader('Content-Length', body.length);
res.end(body);
break;
default:
var body = 'OK';
res.setHeader('Content-Length', body.length);
res.end(body);
}
})
.listen(3001);
// pre-defined
connect()
.use(connect.logger('short'))
.listen(3002);

@ -0,0 +1,14 @@
/**
* Module dependencies.
*/
var connect = require('../');
// $ curl http://localhost:3000/favicon.ico
connect.createServer(
connect.logger()
, connect.favicon()
).listen(3000);

@ -0,0 +1,33 @@
/**
* Module dependencies.
*/
var connect = require('../');
var blog = connect(
connect.router(function(app){
app.get('/', function(req, res){
res.end('list blog posts. try /post/0');
});
app.get('/post/:id', function(req, res){
res.end('got post ' + req.params.id);
});
})
);
var admin = connect(
connect.basicAuth(function(user, pass){ return 'tj' == user && 'tobi' == pass })
, function(req, res){
res.end('admin stuff');
}
);
connect()
.use('/admin', admin)
.use('/blog', blog)
.use(function(req, res){
res.end('try /blog, /admin, or /blog/post/0');
})
.listen(3000);

@ -0,0 +1,17 @@
/**
* Module dependencies.
*/
var connect = require('../');
// $ curl -i http://localhost:3000/
connect(
connect.profiler()
, connect.favicon()
, connect.static(__dirname)
, function(req, res, next){
res.end('hello world');
}
).listen(3000);

@ -0,0 +1,5 @@
<form action="/" method="post" enctype="multipart/form-data">
<input type="text" name="name" placeholder="Name:" />
<input type="file" name="images" multiple="multiple" />
<input type="submit" value="Upload" />
</form>

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

@ -0,0 +1,64 @@
var connect = require('../')
var http = require('http');
var hour = 60 * 60 * 1000;
// maxAge session without the rolling option
// it doesn't update the maxAge value
http.createServer(connect()
.use(connect.cookieParser())
.use(connect.session({ secret : 'keyboard cat',
key : 'NoRolling.sid',
cookie : { maxAge: hour }}))
.use(connect.favicon())
.use(clear)
.use(change)
.use(counter)
).listen(3000);
console.log('port 3000: without rolling, session CANNOT be changed to browser session');
// maxAge session with the rolling option
// it always updates the maxAge value
http.createServer(connect()
.use(connect.cookieParser())
.use(connect.session({ secret : 'keyboard cat',
key : 'Rolling.sid',
cookie : { maxAge: hour },
rolling : true}))
.use(connect.favicon())
.use(clear)
.use(change)
.use(counter)
).listen(3001);
console.log('port 3001: with rolling, session CAN be changed to browser session');
function clear(req, res, next) {
if ('/clear' != req.url) return next();
req.session.regenerate(function(err){});
res.statusCode = 302;
res.setHeader('Location', '/');
res.end();
}
function change(req, res, next) {
if ('/change' != req.url) return next();
req.session.cookie.maxAge = req.session.cookie.maxAge ? null : hour;
res.statusCode = 302;
res.setHeader('Location', '/');
res.end();
}
function counter(req, res) {
req.session.count = req.session.count || 0;
var n = req.session.count++;
var expiration = req.session.cookie.maxAge
? req.session.cookie.maxAge + "msec"
: "browser session";
res.end('<p>Expiration: ' + expiration + '</p>'
+ '<p>Hits: ' + n + '</p>'
+ '<p><a href="/clear">clear session</a></p>'
+ (req.session.cookie.maxAge
? '<p><a href="/change">Change to Browser Session</a></p>'
: '<p><a href="/change">Change to maxAge Session</a></p>'));
}

@ -0,0 +1,198 @@
var connect = require('../')
, http = require('http');
var year = 31557600000;
// large max-age, delegate expiry to the session store.
// for example with connect-redis's .ttl option.
http.createServer(connect()
.use(connect.cookieParser())
.use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: year }}))
.use(connect.favicon())
.use(function(req, res, next){
var sess = req.session;
if (sess.views) {
sess.views++;
res.setHeader('Content-Type', 'text/html');
res.write('<p>views: ' + sess.views + '</p>');
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
res.end();
} else {
sess.views = 1;
res.end('welcome to the session demo. refresh!');
}
})).listen(3007);
console.log('port 3007: 1 minute expiration demo');
// expire sessions within a minute
// /favicon.ico is ignored, and will not
// receive req.session
http.createServer(connect()
.use(connect.cookieParser())
.use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))
.use(connect.favicon())
.use(function(req, res, next){
var sess = req.session;
if (sess.views) {
sess.views++;
res.setHeader('Content-Type', 'text/html');
res.write('<p>views: ' + sess.views + '</p>');
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
res.end();
} else {
sess.views = 1;
res.end('welcome to the session demo. refresh!');
}
})).listen(3006);
console.log('port 3006: 1 minute expiration demo');
// $ npm install connect-redis
try {
var RedisStore = require('connect-redis')(connect);
http.createServer(connect()
.use(connect.cookieParser())
.use(connect.session({
secret: 'keyboard cat',
cookie: { maxAge: 60000 * 3 }
, store: new RedisStore
}))
.use(connect.favicon())
.use(function(req, res, next){
var sess = req.session;
if (sess.views) {
sess.views++;
res.setHeader('Content-Type', 'text/html');
res.end('<p>views: ' + sess.views + '</p>');
} else {
sess.views = 1;
res.end('welcome to the redis demo. refresh!');
}
})).listen(3001);
console.log('port 3001: redis example');
} catch (err) {
console.log('\033[33m');
console.log('failed to start the Redis example.');
console.log('to try it install redis, start redis');
console.log('install connect-redis, and run this');
console.log('script again.');
console.log(' $ redis-server');
console.log(' $ npm install connect-redis');
console.log('\033[0m');
}
// conditional session support by simply
// wrapping middleware with middleware.
var sess = connect.session({ secret: 'keyboard cat', cookie: { maxAge: 5000 }});
http.createServer(connect()
.use(connect.cookieParser())
.use(function(req, res, next){
if ('/foo' == req.url || '/bar' == req.url) {
sess(req, res, next);
} else {
next();
}
})
.use(connect.favicon())
.use(function(req, res, next){
res.end('has session: ' + (req.session ? 'yes' : 'no'));
})).listen(3002);
console.log('port 3002: conditional sessions');
// Session#reload() will update req.session
// without altering .maxAge
// view the page several times, and see that the
// setInterval can still gain access to new
// session data
http.createServer(connect()
.use(connect.cookieParser())
.use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))
.use(connect.favicon())
.use(function(req, res, next){
var sess = req.session
, prev;
if (sess.views) {
res.setHeader('Content-Type', 'text/html');
res.write('<p>views: ' + sess.views + '</p>');
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
sess.views++;
res.end();
} else {
sess.views = 1;
setInterval(function(){
sess.reload(function(){
console.log();
if (prev) console.log('previous views %d, now %d', prev, req.session.views);
console.log('time remaining until expiry: %ds', (req.session.cookie.maxAge / 1000));
prev = req.session.views;
});
}, 3000);
res.end('welcome to the session demo. refresh!');
}
})).listen(3003);
console.log('port 3003: Session#reload() demo');
// by default sessions
// last the duration of
// a user-agent's own session,
// aka while the browser is open.
http.createServer(connect()
.use(connect.cookieParser())
.use(connect.session({ secret: 'keyboard cat' }))
.use(connect.favicon())
.use(function(req, res, next){
var sess = req.session;
if (sess.views) {
res.setHeader('Content-Type', 'text/html');
res.write('<p>views: ' + sess.views + '</p>');
res.end();
sess.views++;
} else {
sess.views = 1;
res.end('welcome to the browser session demo. refresh!');
}
})).listen(3004);
console.log('port 3004: browser-session length sessions');
// persistence example, enter your name!
http.createServer(connect()
.use(connect.bodyParser())
.use(connect.cookieParser())
.use(connect.session({ secret: 'keyboard cat' }))
.use(connect.favicon())
.use(function(req, res, next){
if ('POST' != req.method) return next();
req.session.name = req.body.name;
res.statusCode = 302;
res.setHeader('Location', '/');
res.end();
})
.use(function(req, res, next){
var sess = req.session;
res.setHeader('Content-Type', 'text/html');
if (sess.name) res.write('<p>Hey ' + sess.name + '!</p>');
else res.write('<p>Enter a username:</p>');
res.end('<form action="/" method="post">'
+ '<input type="type" name="name" />'
+ '<input type="submit" value="Save" />'
+ '</form>');
})).listen(3005);
console.log('port 3005: browser-session length sessions persistence example');

@ -0,0 +1,14 @@
/**
* Module dependencies.
*/
var connect = require('../');
connect(
connect.static(__dirname + '/public', { maxAge: 0 })
, function(req, res) {
res.setHeader('Content-Type', 'text/html');
res.end('<img src="/tobi.jpeg" />')
}
).listen(3000);

@ -0,0 +1,37 @@
/**
* Module dependencies.
*/
var connect = require('../');
var fs = require('fs');
connect()
.use(connect.bodyParser({ defer: true }))
.use(form)
.use(upload)
.listen(3000);
function form(req, res, next) {
if ('GET' !== req.method) return next();
res.setHeader('Content-Type', 'text/html');
res.end('<form method="post" enctype="multipart/form-data">'
+ '<input type="file" name="images" multiple="multiple" />'
+ '<input type="submit" value="Upload" />'
+ '</form>');
}
function upload(req, res, next) {
if ('POST' !== req.method) return next();
req.form.on('part', function(part){
// transfer to s3 etc
console.log('upload %s %s', part.name, part.filename);
var out = fs.createWriteStream('/tmp/' + part.filename);
part.pipe(out);
});
req.form.on('close', function(){
res.end('uploaded!');
});
}

@ -0,0 +1,29 @@
/**
* Module dependencies.
*/
var connect = require('../');
connect()
.use(connect.bodyParser())
.use(form)
.use(upload)
.listen(3000);
function form(req, res, next) {
if ('GET' !== req.method) return next();
res.setHeader('Content-Type', 'text/html');
res.end('<form method="post" enctype="multipart/form-data">'
+ '<input type="file" name="images" multiple="multiple" />'
+ '<input type="submit" value="Upload" />'
+ '</form>');
}
function upload(req, res, next) {
if ('POST' !== req.method) return next();
req.files.images.forEach(function(file){
console.log(' uploaded : %s %skb : %s', file.originalFilename, file.size / 1024 | 0, file.path);
});
res.end('Thanks');
}

@ -0,0 +1,31 @@
/**
* Module dependencies.
*/
var connect = require('../');
var account = connect(function(req, res){
var location = 'http://localhost:3000/account/' + req.headers.host.split('.localhost')[0];
res.statusCode = 302;
res.setHeader('Location', location);
res.end('Moved to ' + location);
});
var blog = connect(function(req, res){
res.end('blog app');
});
var main = connect(function(req, res){
if (req.url == '/') return res.end('main app');
if (0 == req.url.indexOf('/account/')) return res.end('viewing user account for ' + req.url.substring(9));
res.statusCode = 404;
res.end();
});
connect(
connect.logger()
, connect.vhost('blog.localhost', blog)
, connect.vhost('*.localhost', account)
, main
).listen(3000);

@ -0,0 +1,2 @@
module.exports = require('./lib/connect');

@ -0,0 +1,81 @@
/*!
* Connect - Cache
* Copyright(c) 2011 Sencha Inc.
* MIT Licensed
*/
/**
* Expose `Cache`.
*/
module.exports = Cache;
/**
* LRU cache store.
*
* @param {Number} limit
* @api private
*/
function Cache(limit) {
this.store = {};
this.keys = [];
this.limit = limit;
}
/**
* Touch `key`, promoting the object.
*
* @param {String} key
* @param {Number} i
* @api private
*/
Cache.prototype.touch = function(key, i){
this.keys.splice(i,1);
this.keys.push(key);
};
/**
* Remove `key`.
*
* @param {String} key
* @api private
*/
Cache.prototype.remove = function(key){
delete this.store[key];
};
/**
* Get the object stored for `key`.
*
* @param {String} key
* @return {Array}
* @api private
*/
Cache.prototype.get = function(key){
return this.store[key];
};
/**
* Add a cache `key`.
*
* @param {String} key
* @return {Array}
* @api private
*/
Cache.prototype.add = function(key){
// initialize store
var len = this.keys.push(key);
// limit reached, invalidate LRU
if (len > this.limit) this.remove(this.keys.shift());
var arr = this.store[key] = [];
arr.createdAt = new Date;
return arr;
};

@ -0,0 +1,92 @@
/*!
* Connect
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter
, proto = require('./proto')
, utils = require('./utils')
, path = require('path')
, basename = path.basename
, fs = require('fs');
// node patches
require('./patch');
// expose createServer() as the module
exports = module.exports = createServer;
/**
* Framework version.
*/
exports.version = require('../package').version;
/**
* Expose mime module.
*/
exports.mime = require('./middleware/static').mime;
/**
* Expose the prototype.
*/
exports.proto = proto;
/**
* Auto-load middleware getters.
*/
exports.middleware = {};
/**
* Expose utilities.
*/
exports.utils = utils;
/**
* Create a new connect server.
*
* @return {Function}
* @api public
*/
function createServer() {
function app(req, res, next){ app.handle(req, res, next); }
utils.merge(app, proto);
utils.merge(app, EventEmitter.prototype);
app.route = '/';
app.stack = [];
for (var i = 0; i < arguments.length; ++i) {
app.use(arguments[i]);
}
return app;
};
/**
* Support old `.createServer()` method.
*/
createServer.createServer = createServer;
/**
* Auto-load bundled middleware with getters.
*/
fs.readdirSync(__dirname + '/middleware').forEach(function(filename){
if (!/\.js$/.test(filename)) return;
var name = basename(filename, '.js');
function load(){ return require('./middleware/' + name); }
exports.middleware.__defineGetter__(name, load);
exports.__defineGetter__(name, load);
});

@ -0,0 +1,50 @@
/**
* Connect is a middleware framework for node,
* shipping with over 18 bundled middleware and a rich selection of
* 3rd-party middleware.
*
* var app = connect()
* .use(connect.logger('dev'))
* .use(connect.static('public'))
* .use(function(req, res){
* res.end('hello world\n');
* })
*
* http.createServer(app).listen(3000);
*
* Installation:
*
* $ npm install connect
*
* Middleware:
*
* - [basicAuth](https://github.com/expressjs/basic-auth-connect) basic http authentication
* - [cookieParser](https://github.com/expressjs/cookie-parser) cookie parser
* - [compress](https://github.com/expressjs/compression) Gzip compression middleware
* - [csrf](https://github.com/expressjs/csurf) Cross-site request forgery protection
* - [directory](https://github.com/expressjs/serve-index) directory listing middleware
* - [errorHandler](https://github.com/expressjs/errorhandler) flexible error handler
* - [favicon](https://github.com/expressjs/favicon) efficient favicon server (with default icon)
* - [json](https://github.com/expressjs/body-parser) application/json parser
* - [logger](https://github.com/expressjs/morgan) request logger with custom format support
* - [methodOverride](https://github.com/expressjs/method-override) faux HTTP method support
* - [responseTime](https://github.com/expressjs/response-time) calculates response-time and exposes via X-Response-Time
* - [session](https://github.com/expressjs/session) session management support with bundled MemoryStore
* - [static](https://github.com/expressjs/serve-static) streaming static file server supporting `Range` and more
* - [timeout](https://github.com/expressjs/timeout) request timeouts
* - [urlencoded](https://github.com/expressjs/body-parser) application/x-www-form-urlencoded parser
* - [vhost](https://github.com/expressjs/vhost) virtual host sub-domain mapping middleware
* - [bodyParser](bodyParser.html) extensible request body parser
* - [multipart](multipart.html) multipart/form-data parser
* - [cookieSession](cookieSession.html) cookie-based session support
* - [staticCache](staticCache.html) memory cache layer for the static() middleware
* - [limit](limit.html) limit the bytesize of request bodies
* - [query](query.html) automatic querystring parser, populating `req.query`
*
* Links:
*
* - list of [3rd-party](https://github.com/senchalabs/connect/wiki) middleware
* - GitHub [repository](http://github.com/senchalabs/connect)
*
*/

@ -0,0 +1,24 @@
/*!
* Connect - basicAuth
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Basic Auth:
*
* Enfore basic authentication by providing a `callback(user, pass)`,
* which must return `true` in order to gain access. Alternatively an async
* method is provided as well, invoking `callback(user, pass, callback)`. Populates
* `req.user`. The final alternative is simply passing username / password
* strings.
*
* See [basic-auth-connect](https://github.com/expressjs/basic-auth-connect)
*
* @param {Function|String} callback or username
* @param {String} realm
* @api public
*/
module.exports = require('basic-auth-connect');

@ -0,0 +1,68 @@
/*!
* Connect - bodyParser
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var multipart = require('./multipart')
, urlencoded = require('./urlencoded')
, json = require('./json');
/**
* Body parser:
*
* Status: the multipart body parser will be removed in Connect 3.
*
* Parse request bodies, supports _application/json_,
* _application/x-www-form-urlencoded_, and _multipart/form-data_.
*
* This is equivalent to:
*
* app.use(connect.json());
* app.use(connect.urlencoded());
* app.use(connect.multipart());
*
* Examples:
*
* connect()
* .use(connect.bodyParser())
* .use(function(req, res) {
* res.end('viewing user ' + req.body.user.name);
* });
*
* $ curl -d 'user[name]=tj' http://local/
* $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/
*
* View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info.
*
* If you wish to create your own body parser, you may be interested in:
*
* - [raw-body](https://github.com/stream-utils/raw-body)
* - [body](https://github.com/raynos/body)
*
* @param {Object} options
* @return {Function}
* @api public
*/
exports = module.exports = function bodyParser(options){
var _urlencoded = urlencoded(options)
, _multipart = multipart(options)
, _json = json(options);
return function bodyParser(req, res, next) {
_json(req, res, function(err){
if (err) return next(err);
_urlencoded(req, res, function(err){
if (err) return next(err);
_multipart(req, res, next);
});
});
}
};

@ -0,0 +1,20 @@
/*!
* Connect - compress
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Compress:
*
* Compress response data with gzip/deflate.
*
* See [compression](https://github.com/expressjs/compression)
*
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = require('compression');

@ -0,0 +1,19 @@
/*!
* Connect - cookieParser
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Cookie parser:
*
* See [cookie-parser](https://github.com/expressjs/cookie-parser)
*
* @param {String} secret
* @return {Function}
* @api public
*/
module.exports = require('cookie-parser');

@ -0,0 +1,122 @@
/*!
* Connect - cookieSession
* Copyright(c) 2011 Sencha Inc.
* MIT Licensed
*/
/**
* Module dependencies.
*/
var utils = require('./../utils')
, Cookie = require('express-session').Cookie
, debug = require('debug')('connect:cookieSession')
, signature = require('cookie-signature')
, onHeaders = require('on-headers')
, url = require('url');
/**
* Cookie Session:
*
* Cookie session middleware.
*
* var app = connect();
* app.use(connect.cookieParser());
* app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }}));
*
* Options:
*
* - `key` cookie name defaulting to `connect.sess`
* - `secret` prevents cookie tampering
* - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }`
* - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto")
*
* Clearing sessions:
*
* To clear the session simply set its value to `null`,
* `cookieSession()` will then respond with a 1970 Set-Cookie.
*
* req.session = null;
*
* If you are interested in more sophisticated solutions,
* you may be interested in:
*
* - [client-sessions](https://github.com/mozilla/node-client-sessions)
*
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = function cookieSession(options){
// TODO: utilize Session/Cookie to unify API
options = options || {};
var key = options.key || 'connect.sess'
, trustProxy = options.proxy;
return function cookieSession(req, res, next) {
// req.secret is for backwards compatibility
var secret = options.secret || req.secret;
if (!secret) throw new Error('`secret` option required for cookie sessions');
// default session
req.session = {};
var cookie = req.session.cookie = new Cookie(options.cookie);
// pathname mismatch
var originalPath = url.parse(req.originalUrl).pathname;
if (0 != originalPath.indexOf(cookie.path)) return next();
// cookieParser secret
if (!options.secret && req.secret) {
req.session = req.signedCookies[key] || {};
req.session.cookie = cookie;
} else {
// TODO: refactor
var rawCookie = req.cookies[key];
if (rawCookie) {
var unsigned = utils.parseSignedCookie(rawCookie, secret);
if (unsigned) {
var original = unsigned;
req.session = utils.parseJSONCookie(unsigned) || {};
req.session.cookie = cookie;
}
}
}
onHeaders(res, function(){
// removed
if (!req.session) {
debug('clear session');
cookie.expires = new Date(0);
res.setHeader('Set-Cookie', cookie.serialize(key, ''));
return;
}
delete req.session.cookie;
// check security
var proto = (req.headers['x-forwarded-proto'] || '').toLowerCase()
, tls = req.connection.encrypted || (trustProxy && 'https' == proto.split(/\s*,\s*/)[0]);
// only send secure cookies via https
if (cookie.secure && !tls) return debug('not secured');
// serialize
debug('serializing %j', req.session);
var val = 'j:' + JSON.stringify(req.session);
// compare data, no need to set-cookie if unchanged
if (original == val) return debug('unmodified session');
// set-cookie
val = 's:' + signature.sign(val, secret);
val = cookie.serialize(key, val);
debug('set-cookie %j', cookie);
res.setHeader('Set-Cookie', val);
});
next();
};
};

@ -0,0 +1,18 @@
/*!
* Connect - csrf
* Copyright(c) 2011 Sencha Inc.
* MIT Licensed
*/
/**
* Anti CSRF:
*
* CSRF protection middleware.
*
* See [csurf](https://github.com/expressjs/csurf)
*
* @param {Object} options
* @api public
*/
module.exports = require('csurf');

@ -0,0 +1,20 @@
/*!
* Connect - directory
* Copyright(c) 2011 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Directory:
*
* See [serve-index](https://github.com/expressjs/serve-index)
*
* @param {String} root
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = require('serve-index');

@ -0,0 +1,17 @@
/*!
* Connect - errorHandler
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Error handler:
*
* See [errorHandler](https://github.com/expressjs/errorhandler)
*
* @return {Function}
* @api public
*/
module.exports = require('errorhandler');

@ -0,0 +1,34 @@
/*!
* Connect - favicon
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var path = require('path');
var serveFavicon = require('serve-favicon');
var defaultPath = path.join(__dirname, '..', 'public', 'favicon.ico');
/**
* Favicon:
*
* By default serves the connect favicon, or the favicon
* located by the given `path`.
*
* See [serve-favicon](https://github.com/expressjs/serve-favicon)
*
* @param {String|Buffer} path
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = function favicon(path, options){
path = path || defaultPath;
return serveFavicon(path, options);
};

@ -0,0 +1,52 @@
/*!
* Connect - json
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var bodyParser = require('body-parser');
var utils = require('../utils');
/**
* JSON:
*
* See [body-parser](https://github.com/expressjs/body-parser)
*
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = function json(options) {
var opts = utils.merge({
limit: '1mb',
type: ['application/json', 'application/*+json']
}, options);
// back-compat verify function
if (typeof opts.verify === 'function') {
opts.verify = convertVerify(opts.verify);
}
return bodyParser.json(opts);
};
/**
* Convert old verify signature to body-parser version.
*
* @param {Function} verify
* @return {Function}
* @api private
*/
function convertVerify(verify) {
return function (req, res, buf, encoding) {
verify(req, res, buf.toString(encoding));
};
}

@ -0,0 +1,89 @@
/*!
* Connect - limit
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var parseBytes = require('bytes');
var utils = require('../utils');
var brokenPause = utils.brokenPause;
/**
* Limit:
*
* Status: Deprecated. This middleware will be removed in Connect 3.0.
* If you still wish to use some type of limit middleware,
* you may be interested in:
*
* - [raw-body](https://github.com/stream-utils/raw-body)
*
* Limit request bodies to the given size in `bytes`.
*
* A string representation of the bytesize may also be passed,
* for example "5mb", "200kb", "1gb", etc.
*
* connect()
* .use(connect.limit('5.5mb'))
* .use(handleImageUpload)
*
* @param {Number|String} bytes
* @return {Function}
* @api public
*/
module.exports = function limit(bytes){
if ('string' == typeof bytes) bytes = parseBytes(bytes);
if ('number' != typeof bytes) throw new Error('limit() bytes required');
return function limit(req, res, next){
var received = 0
, len = req.headers['content-length']
? parseInt(req.headers['content-length'], 10)
: null;
// self-awareness
if (req._limit) return next();
req._limit = true;
// limit by content-length
if (len && len > bytes) return next(utils.error(413));
// limit
if (brokenPause) {
listen();
} else {
req.on('newListener', function handler(event) {
if (event !== 'data') return;
req.removeListener('newListener', handler);
// Start listening at the end of the current loop
// otherwise the request will be consumed too early.
// Sideaffect is `limit` will miss the first chunk,
// but that's not a big deal.
// Unfortunately, the tests don't have large enough
// request bodies to test this.
process.nextTick(listen);
});
};
next();
function listen() {
req.on('data', function(chunk) {
received += Buffer.isBuffer(chunk)
? chunk.length :
Buffer.byteLength(chunk);
if (received > bytes) req.destroy();
});
};
};
};
module.exports = utils.deprecate(module.exports,
'limit: Restrict request size at location of read');

@ -0,0 +1,20 @@
/*!
* Connect - logger
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Logger:
*
* Log requests with the given `options` or a `format` string.
*
* See [morgan](https://github.com/expressjs/morgan)
*
* @param {String|Function|Object} format or options
* @return {Function}
* @api public
*/
module.exports = require('morgan');

@ -0,0 +1,47 @@
/*!
* Connect - methodOverride
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var methodOverride = require('method-override');
var utils = require('../utils');
/**
* Method Override:
*
* See [method-override](https://github.com/expressjs/method-override)
*
* @param {String} key
* @return {Function}
* @api public
*/
module.exports = function(key){
// this is a shim to keep the interface working with method-override@2
var opts = { methods: null };
var prop = key || '_method';
var _headerOverride = methodOverride('X-HTTP-Method-Override', opts);
var _bodyOverride = methodOverride(function(req){
if (req.body && typeof req.body === 'object' && prop in req.body) {
var method = req.body[prop];
delete req.body[prop];
return method;
}
}, opts);
return function(req, res, next){
_bodyOverride(req, res, function(err){
if (err) return next(err);
_headerOverride(req, res, next);
});
};
};
module.exports = utils.deprecate(module.exports,
'methodOverride: use method-override module directly');

@ -0,0 +1,168 @@
/*!
* Connect - multipart
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var multiparty = require('multiparty')
, typeis = require('type-is')
, _limit = require('./limit')
, utils = require('../utils')
, qs = require('qs');
/**
* Multipart:
*
* Status: Deprecated. The multipart parser will be removed in Connect 3.0.
* Please use one of the following parsers/middleware directly:
*
* - [formidable](https://github.com/felixge/node-formidable)
* - [connect-multiparty](https://github.com/superjoe30/connect-multiparty) or [multiparty]
* - [connect-busboy](https://github.com/mscdex/connect-busboy) or [busboy](https://github.com/mscdex/busboy)
*
* Parse multipart/form-data request bodies,
* providing the parsed object as `req.body`
* and `req.files`.
*
* Configuration:
*
* The options passed are merged with [multiparty](https://github.com/superjoe30/node-multiparty)'s
* `Form` object, allowing you to configure the upload directory,
* size limits, etc. For example if you wish to change the upload dir do the following.
*
* app.use(connect.multipart({ uploadDir: path }));
*
* Options:
*
* - `limit` byte limit defaulting to [100mb]
* - `defer` defers processing and exposes the multiparty form object as `req.form`.
* `next()` is called without waiting for the form's "end" event.
* This option is useful if you need to bind to the "progress" or "part" events, for example.
*
* Temporary Files:
*
* By default temporary files are used, stored in `os.tmpDir()`. These
* are not automatically garbage collected, you are in charge of moving them
* or deleting them. When `defer` is not used and these files are created you
* may refernce them via the `req.files` object.
*
* req.files.images.forEach(function(file){
* console.log(' uploaded : %s %skb : %s', file.originalFilename, file.size / 1024 | 0, file.path);
* });
*
* It is highly recommended to monitor and clean up tempfiles in any production
* environment, you may use tools like [reap](https://github.com/visionmedia/reap)
* to do so.
*
* Streaming:
*
* When `defer` is used files are _not_ streamed to tmpfiles, you may
* access them via the "part" events and stream them accordingly:
*
* req.form.on('part', function(part){
* // transfer to s3 etc
* console.log('upload %s %s', part.name, part.filename);
* var out = fs.createWriteStream('/tmp/' + part.filename);
* part.pipe(out);
* });
*
* req.form.on('close', function(){
* res.end('uploaded!');
* });
*
* @param {Object} options
* @return {Function}
* @api public
*/
exports = module.exports = function(options){
options = options || {};
var limit = _limit(options.limit || '100mb');
return function multipart(req, res, next) {
if (req._body) return next();
req.body = req.body || {};
req.files = req.files || {};
// ignore GET
if ('GET' == req.method || 'HEAD' == req.method) return next();
// check Content-Type
if (!typeis(req, 'multipart')) return next();
// flag as parsed
req._body = true;
// parse
limit(req, res, function(err){
if (err) return next(err);
var form = new multiparty.Form(options)
, data = {}
, files = {}
, done;
Object.keys(options).forEach(function(key){
form[key] = options[key];
});
function ondata(name, val, data){
if (Array.isArray(data[name])) {
data[name].push(val);
} else if (data[name]) {
data[name] = [data[name], val];
} else {
data[name] = val;
}
}
form.on('field', function(name, val){
ondata(name, val, data);
});
if (!options.defer) {
form.on('file', function(name, val){
val.name = val.originalFilename;
val.type = val.headers['content-type'] || null;
ondata(name, val, files);
});
}
form.on('error', function(err){
if (!options.defer) {
err.status = 400;
next(err);
}
done = true;
});
form.on('close', function(){
if (done) return;
try {
req.body = qs.parse(data);
req.files = qs.parse(files);
} catch (err) {
form.emit('error', err);
return;
}
if (!options.defer) next();
});
form.parse(req);
if (options.defer) {
req.form = form;
next();
}
});
}
};
module.exports = utils.deprecate(module.exports,
'multipart: use parser (multiparty, busboy, formidable) directly');

@ -0,0 +1,47 @@
/*!
* Connect - query
* Copyright(c) 2011 TJ Holowaychuk
* Copyright(c) 2011 Sencha Inc.
* MIT Licensed
*/
/**
* Module dependencies.
*/
var qs = require('qs')
, parseurl = require('parseurl');
/**
* Query:
*
* Automatically parse the query-string when available,
* populating the `req.query` object using
* [qs](https://github.com/visionmedia/node-querystring).
*
* Examples:
*
* connect()
* .use(connect.query())
* .use(function(req, res){
* res.end(JSON.stringify(req.query));
* });
*
* The `options` passed are provided to qs.parse function.
*
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = function query(options){
return function query(req, res, next){
if (!req.query) {
req.query = ~req.url.indexOf('?')
? qs.parse(parseurl(req).query, options)
: {};
}
next();
};
};

@ -0,0 +1,17 @@
/*!
* Connect - responseTime
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Reponse time:
*
* See [response-time](https://github.com/expressjs/response-time)
*
* @return {Function}
* @api public
*/
module.exports = require('response-time');

@ -0,0 +1,20 @@
/*!
* Connect - session
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Session:
*
* Setup session store with the given `options`.
*
* See [express-session](https://github.com/expressjs/session)
*
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = require('express-session');

@ -0,0 +1,19 @@
/*!
* Connect - static
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Static:
*
* See [serve-static](https://github.com/expressjs/serve-static)
*
* @param {String} root
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = require('serve-static');

@ -0,0 +1,237 @@
/*!
* Connect - staticCache
* Copyright(c) 2011 Sencha Inc.
* MIT Licensed
*/
/**
* Module dependencies.
*/
var utils = require('../utils')
, parseurl = require('parseurl')
, Cache = require('../cache')
, fresh = require('fresh');
/**
* Static cache:
*
* Status: Deprecated. This middleware will be removed in
* Connect 3.0. You may be interested in:
*
* - [st](https://github.com/isaacs/st)
*
* Enables a memory cache layer on top of
* the `static()` middleware, serving popular
* static files.
*
* By default a maximum of 128 objects are
* held in cache, with a max of 256k each,
* totalling ~32mb.
*
* A Least-Recently-Used (LRU) cache algo
* is implemented through the `Cache` object,
* simply rotating cache objects as they are
* hit. This means that increasingly popular
* objects maintain their positions while
* others get shoved out of the stack and
* garbage collected.
*
* Benchmarks:
*
* static(): 2700 rps
* node-static: 5300 rps
* static() + staticCache(): 7500 rps
*
* Options:
*
* - `maxObjects` max cache objects [128]
* - `maxLength` max cache object length 256kb
*
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = function staticCache(options){
var options = options || {}
, cache = new Cache(options.maxObjects || 128)
, maxlen = options.maxLength || 1024 * 256;
return function staticCache(req, res, next){
var key = cacheKey(req)
, ranges = req.headers.range
, hasCookies = req.headers.cookie
, hit = cache.get(key);
// cache static
// TODO: change from staticCache() -> cache()
// and make this work for any request
req.on('static', function(stream){
var headers = res._headers
, cc = utils.parseCacheControl(headers['cache-control'] || '')
, contentLength = headers['content-length']
, hit;
// dont cache set-cookie responses
if (headers['set-cookie']) return hasCookies = true;
// dont cache when cookies are present
if (hasCookies) return;
// ignore larger files
if (!contentLength || contentLength > maxlen) return;
// don't cache partial files
if (headers['content-range']) return;
// dont cache items we shouldn't be
// TODO: real support for must-revalidate / no-cache
if ( cc['no-cache']
|| cc['no-store']
|| cc['private']
|| cc['must-revalidate']) return;
// if already in cache then validate
if (hit = cache.get(key)){
if (headers.etag == hit[0].etag) {
hit[0].date = new Date;
return;
} else {
cache.remove(key);
}
}
// validation notifiactions don't contain a steam
if (null == stream) return;
// add the cache object
var arr = [];
// store the chunks
stream.on('data', function(chunk){
arr.push(chunk);
});
// flag it as complete
stream.on('end', function(){
var cacheEntry = cache.add(key);
delete headers['x-cache']; // Clean up (TODO: others)
cacheEntry.push(200);
cacheEntry.push(headers);
cacheEntry.push.apply(cacheEntry, arr);
});
});
if (req.method == 'GET' || req.method == 'HEAD') {
if (ranges) {
next();
} else if (!hasCookies && hit && !mustRevalidate(req, hit)) {
res.setHeader('X-Cache', 'HIT');
respondFromCache(req, res, hit);
} else {
res.setHeader('X-Cache', 'MISS');
next();
}
} else {
next();
}
}
};
module.exports = utils.deprecate(module.exports,
'staticCache: use varnish or similar reverse proxy caches');
/**
* Respond with the provided cached value.
* TODO: Assume 200 code, that's iffy.
*
* @param {Object} req
* @param {Object} res
* @param {Object} cacheEntry
* @return {String}
* @api private
*/
function respondFromCache(req, res, cacheEntry) {
var status = cacheEntry[0]
, headers = utils.merge({}, cacheEntry[1])
, content = cacheEntry.slice(2);
headers.age = (new Date - new Date(headers.date)) / 1000 || 0;
switch (req.method) {
case 'HEAD':
res.writeHead(status, headers);
res.end();
break;
case 'GET':
if (fresh(req.headers, headers)) {
headers['content-length'] = 0;
res.writeHead(304, headers);
res.end();
} else {
res.writeHead(status, headers);
function write() {
while (content.length) {
if (false === res.write(content.shift())) {
res.once('drain', write);
return;
}
}
res.end();
}
write();
}
break;
default:
// This should never happen.
res.writeHead(500, '');
res.end();
}
}
/**
* Determine whether or not a cached value must be revalidated.
*
* @param {Object} req
* @param {Object} cacheEntry
* @return {String}
* @api private
*/
function mustRevalidate(req, cacheEntry) {
var cacheHeaders = cacheEntry[1]
, reqCC = utils.parseCacheControl(req.headers['cache-control'] || '')
, cacheCC = utils.parseCacheControl(cacheHeaders['cache-control'] || '')
, cacheAge = (new Date - new Date(cacheHeaders.date)) / 1000 || 0;
if ( cacheCC['no-cache']
|| cacheCC['must-revalidate']
|| cacheCC['proxy-revalidate']) return true;
if (reqCC['no-cache']) return true;
if (null != reqCC['max-age']) return reqCC['max-age'] < cacheAge;
if (null != cacheCC['max-age']) return cacheCC['max-age'] < cacheAge;
return false;
}
/**
* The key to use in the cache. For now, this is the URL path and query.
*
* 'http://example.com?key=value' -> '/?key=value'
*
* @param {Object} req
* @return {String}
* @api private
*/
function cacheKey(req) {
return parseurl(req).path;
}

@ -0,0 +1,23 @@
/*!
* Connect - timeout
* Ported from https://github.com/LearnBoost/connect-timeout
* MIT Licensed
*/
/**
* Module dependencies.
*/
var debug = require('debug')('connect:timeout');
/**
* Timeout:
*
* See [connect-timeout](https://github.com/expressjs/timeout)
*
* @param {Number} ms
* @return {Function}
* @api public
*/
module.exports = require('connect-timeout');

@ -0,0 +1,50 @@
/*!
* Connect - urlencoded
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var bodyParser = require('body-parser');
var utils = require('../utils');
/**
* Urlencoded:
*
* See [body-parser](https://github.com/expressjs/body-parser)
*
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = function urlencoded(options) {
var opts = utils.merge({
limit: '1mb'
}, options);
// back-compat verify function
if (typeof opts.verify === 'function') {
opts.verify = convertVerify(opts.verify);
}
return bodyParser.urlencoded(opts);
};
/**
* Convert old verify signature to body-parser version.
*
* @param {Function} verify
* @return {Function}
* @api private
*/
function convertVerify(verify) {
return function (req, res, buf, encoding) {
verify(req, res, buf.toString(encoding));
};
}

@ -0,0 +1,20 @@
/*!
* Connect - vhost
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Vhost:
*
* See [vhost](https://github.com/expressjs/vhost)
*
* @param {String} hostname
* @param {Server} server
* @return {Function}
* @api public
*/
module.exports = require('vhost');

@ -0,0 +1,157 @@
/*!
* Connect
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var cookie = require('cookie');
var http = require('http');
var onHeaders = require('on-headers');
var utils = require('./utils')
, res = http.ServerResponse.prototype
, addListener = res.addListener
, setHeader = res.setHeader;
/**
* Deprecated proxy for .on('header', ...)
*/
var attachHeaderListener = utils.deprecate(onHeaders,
'res.on("header"): use on-headers module directly');
// apply only once
if (!res._hasConnectPatch) {
/**
* Provide a public "header sent" flag
* until node does.
*
* @return {Boolean}
* @api public
*/
Object.defineProperty(res, 'headerSent', {
configurable: true,
enumerable: true,
get: utils.deprecate(headersSent, 'res.headerSent: use standard res.headersSent')
});
if (!('headersSent' in res)) {
/**
* Provide the public "header sent" flag
* added in node.js 0.10.
*
* @return {Boolean}
* @api public
*/
Object.defineProperty(res, 'headersSent', {
configurable: true,
enumerable: true,
get: headersSent
});
}
/**
* Set cookie `name` to `val`, with the given `options`.
*
* Options:
*
* - `maxAge` max-age in milliseconds, converted to `expires`
* - `path` defaults to "/"
*
* @param {String} name
* @param {String} val
* @param {Object} options
* @api public
*/
res.cookie = function(name, val, options){
options = utils.merge({}, options);
if ('maxAge' in options) {
options.expires = new Date(Date.now() + options.maxAge);
options.maxAge /= 1000;
}
if (null == options.path) options.path = '/';
this.setHeader('Set-Cookie', cookie.serialize(name, String(val), options));
};
/**
* Append additional header `field` with value `val`.
*
* @param {String} field
* @param {String} val
* @api public
*/
res.appendHeader = function appendHeader(field, val){
var prev = this.getHeader(field);
if (!prev) return setHeader.call(this, field, val);
// concat the new and prev vals
val = Array.isArray(prev) ? prev.concat(val)
: Array.isArray(val) ? [prev].concat(val)
: [prev, val];
return setHeader.call(this, field, val);
};
/**
* Set header `field` to `val`, special-casing
* the `Set-Cookie` field for multiple support.
*
* @param {String} field
* @param {String} val
* @api public
*/
res.setHeader = function(field, val){
var key = field.toLowerCase()
, prev;
// special-case Set-Cookie
if ('set-cookie' == key) return this.appendHeader(field, val);
// charset
if ('content-type' == key && this.charset) {
val = utils.setCharset(val, this.charset, true);
}
return setHeader.call(this, field, val);
};
/**
* Proxy to emit "header" event.
*/
res.on = function(type, listener){
if (type === 'header') {
attachHeaderListener(this, listener);
return this;
}
return addListener.apply(this, arguments);
};
res._hasConnectPatch = true;
}
/**
* Determine if headers sent.
*
* @return {Boolean}
* @api private
*/
function headersSent(){
return Boolean(this._header);
}

@ -0,0 +1,234 @@
/*!
* Connect - HTTPServer
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var escapeHtml = require('escape-html');
var http = require('http')
, parseurl = require('parseurl')
, debug = require('debug')('connect:dispatcher');
// prototype
var app = module.exports = {};
// environment
var env = process.env.NODE_ENV || 'development';
/**
* Utilize the given middleware `handle` to the given `route`,
* defaulting to _/_. This "route" is the mount-point for the
* middleware, when given a value other than _/_ the middleware
* is only effective when that segment is present in the request's
* pathname.
*
* For example if we were to mount a function at _/admin_, it would
* be invoked on _/admin_, and _/admin/settings_, however it would
* not be invoked for _/_, or _/posts_.
*
* Examples:
*
* var app = connect();
* app.use(connect.favicon());
* app.use(connect.logger());
* app.use(connect.static(__dirname + '/public'));
*
* If we wanted to prefix static files with _/public_, we could
* "mount" the `static()` middleware:
*
* app.use('/public', connect.static(__dirname + '/public'));
*
* This api is chainable, so the following is valid:
*
* connect()
* .use(connect.favicon())
* .use(connect.logger())
* .use(connect.static(__dirname + '/public'))
* .listen(3000);
*
* @param {String|Function|Server} route, callback or server
* @param {Function|Server} callback or server
* @return {Server} for chaining
* @api public
*/
app.use = function(route, fn){
// default route to '/'
if ('string' != typeof route) {
fn = route;
route = '/';
}
// wrap sub-apps
if ('function' == typeof fn.handle) {
var server = fn;
fn.route = route;
fn = function(req, res, next){
server.handle(req, res, next);
};
}
// wrap vanilla http.Servers
if (fn instanceof http.Server) {
fn = fn.listeners('request')[0];
}
// strip trailing slash
if ('/' == route[route.length - 1]) {
route = route.slice(0, -1);
}
// add the middleware
debug('use %s %s', route || '/', fn.name || 'anonymous');
this.stack.push({ route: route, handle: fn });
return this;
};
/**
* Handle server requests, punting them down
* the middleware stack.
*
* @api private
*/
app.handle = function(req, res, out) {
var stack = this.stack
, search = 1 + req.url.indexOf('?')
, pathlength = search ? search - 1 : req.url.length
, fqdn = 1 + req.url.substr(0, pathlength).indexOf('://')
, protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : ''
, removed = ''
, slashAdded = false
, index = 0;
function next(err) {
var layer, path, c;
if (slashAdded) {
req.url = req.url.substr(1);
slashAdded = false;
}
req.url = protohost + removed + req.url.substr(protohost.length);
req.originalUrl = req.originalUrl || req.url;
removed = '';
// next callback
layer = stack[index++];
// all done
if (!layer) {
// delegate to parent
if (out) return out(err);
// unhandled error
if (err) {
// default to 500
if (res.statusCode < 400) res.statusCode = 500;
debug('default %s', res.statusCode);
// respect err.status
if (err.status) res.statusCode = err.status;
// production gets a basic error message
var msg = 'production' == env
? http.STATUS_CODES[res.statusCode]
: err.stack || err.toString();
msg = escapeHtml(msg);
// log to stderr in a non-test env
if ('test' != env) console.error(err.stack || err.toString());
if (res.headersSent) return req.socket.destroy();
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Length', Buffer.byteLength(msg));
if ('HEAD' == req.method) return res.end();
res.end(msg);
} else if (!res.headersSent) {
debug('default 404');
res.statusCode = 404;
res.setHeader('Content-Type', 'text/html');
if ('HEAD' == req.method) return res.end();
res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n');
}
return;
}
try {
path = parseurl(req).pathname;
if (undefined == path) path = '/';
// skip this layer if the route doesn't match.
if (0 != path.toLowerCase().indexOf(layer.route.toLowerCase())) return next(err);
c = path[layer.route.length];
if (c && '/' != c && '.' != c) return next(err);
// Call the layer handler
// Trim off the part of the url that matches the route
removed = layer.route;
req.url = protohost + req.url.substr(protohost.length + removed.length);
// Ensure leading slash
if (!fqdn && '/' != req.url[0]) {
req.url = '/' + req.url;
slashAdded = true;
}
debug('%s %s : %s', layer.handle.name || 'anonymous', layer.route, req.originalUrl);
var arity = layer.handle.length;
if (err) {
if (arity === 4) {
layer.handle(err, req, res, next);
} else {
next(err);
}
} else if (arity < 4) {
layer.handle(req, res, next);
} else {
next();
}
} catch (e) {
next(e);
}
}
next();
};
/**
* Listen for connections.
*
* This method takes the same arguments
* as node's `http.Server#listen()`.
*
* HTTP and HTTPS:
*
* If you run your application both as HTTP
* and HTTPS you may wrap them individually,
* since your Connect "server" is really just
* a JavaScript `Function`.
*
* var connect = require('connect')
* , http = require('http')
* , https = require('https');
*
* var app = connect();
*
* http.createServer(app).listen(80);
* https.createServer(options, app).listen(443);
*
* @return {http.Server}
* @api public
*/
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

@ -0,0 +1,474 @@
/*!
* Connect - utils
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var http = require('http')
, crypto = require('crypto')
, parseurl = require('parseurl')
, sep = require('path').sep
, signature = require('cookie-signature')
, typeis = require('type-is')
, deprecate = require('util').deprecate
, nodeVersion = process.versions.node.split('.');
/**
* Simple detection of charset parameter in content-type
*/
var charsetRegExp = /;\s*charset\s*=/;
/**
* pause is broken in node < 0.10
*/
exports.brokenPause = parseInt(nodeVersion[0], 10) === 0
&& parseInt(nodeVersion[1], 10) < 10;
/**
* Deprecate function, like core `util.deprecate`,
* but with NODE_ENV and color support.
*
* @param {Function} fn
* @param {String} msg
* @return {Function}
* @api private
*/
exports.deprecate = function(fn, msg){
if (process.env.NODE_ENV === 'test') return fn;
// prepend module name
msg = 'connect: ' + msg;
if (process.stderr.isTTY) {
// colorize
msg = '\x1b[31;1m' + msg + '\x1b[0m';
}
return deprecate(fn, msg);
};
/**
* Return `true` if the request has a body, otherwise return `false`.
*
* @param {IncomingMessage} req
* @return {Boolean}
* @api private
*/
exports.hasBody = exports.deprecate(typeis.hasBody,
'utils.hasBody: use type-is module directly');
/**
* Extract the mime type from the given request's
* _Content-Type_ header.
*
* @param {IncomingMessage} req
* @return {String}
* @api private
*/
exports.mime = function(req) {
var str = req.headers['content-type'] || ''
, i = str.indexOf(';');
return ~i ? str.slice(0, i) : str;
};
exports.mime = exports.deprecate(exports.mime,
'utils.mime: use type-is directly for mime comparisons');
/**
* Generate an `Error` from the given status `code`
* and optional `msg`.
*
* @param {Number} code
* @param {String} msg
* @return {Error}
* @api private
*/
exports.error = function(code, msg){
var err = new Error(msg || http.STATUS_CODES[code]);
err.status = code;
return err;
};
/**
* Return md5 hash of the given string and optional encoding,
* defaulting to hex.
*
* utils.md5('wahoo');
* // => "e493298061761236c96b02ea6aa8a2ad"
*
* @param {String} str
* @param {String} encoding
* @return {String}
* @api private
*/
exports.md5 = function(str, encoding){
return crypto
.createHash('md5')
.update(str, 'utf8')
.digest(encoding || 'hex');
};
exports.md5 = exports.deprecate(exports.md5,
'utils.md5: use crypto directly for hashing');
/**
* Merge object b with object a.
*
* var a = { foo: 'bar' }
* , b = { bar: 'baz' };
*
* utils.merge(a, b);
* // => { foo: 'bar', bar: 'baz' }
*
* @param {Object} a
* @param {Object} b
* @return {Object}
* @api private
*/
exports.merge = function(a, b){
if (a && b) {
for (var key in b) {
a[key] = b[key];
}
}
return a;
};
/**
* Escape the given string of `html`.
*
* @param {String} html
* @return {String}
* @api private
*/
exports.escape = function(html){
return String(html)
.replace(/&(?!\w+;)/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
};
exports.escape = exports.deprecate(exports.escape,
'utils.escape: use escape-html module directly');
/**
* Sign the given `val` with `secret`.
*
* @param {String} val
* @param {String} secret
* @return {String}
* @api private
*/
exports.sign = exports.deprecate(signature.sign,
'utils.sign: use cookie-signature module directly');
/**
* Unsign and decode the given `val` with `secret`,
* returning `false` if the signature is invalid.
*
* @param {String} val
* @param {String} secret
* @return {String|Boolean}
* @api private
*/
exports.unsign = exports.deprecate(signature.unsign,
'utils.unsign: use cookie-signature module directly');
/**
* Parse signed cookies, returning an object
* containing the decoded key/value pairs,
* while removing the signed key from `obj`.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
exports.parseSignedCookies = function(obj, secret){
var ret = {};
Object.keys(obj).forEach(function(key){
var val = obj[key];
if (0 == val.indexOf('s:')) {
val = signature.unsign(val.slice(2), secret);
if (val) {
ret[key] = val;
delete obj[key];
}
}
});
return ret;
};
exports.parseSignedCookies = exports.deprecate(exports.parseSignedCookies,
'utils.parseSignedCookies: this private api moved with cookie-parser');
/**
* Parse a signed cookie string, return the decoded value
*
* @param {String} str signed cookie string
* @param {String} secret
* @return {String} decoded value
* @api private
*/
exports.parseSignedCookie = function(str, secret){
return 0 == str.indexOf('s:')
? signature.unsign(str.slice(2), secret)
: str;
};
/**
* Parse JSON cookies.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
exports.parseJSONCookies = function(obj){
Object.keys(obj).forEach(function(key){
var val = obj[key];
var res = exports.parseJSONCookie(val);
if (res) obj[key] = res;
});
return obj;
};
exports.parseJSONCookies = exports.deprecate(exports.parseJSONCookies,
'utils.parseJSONCookies: this private api moved with cookie-parser');
/**
* Parse JSON cookie string
*
* @param {String} str
* @return {Object} Parsed object or null if not json cookie
* @api private
*/
exports.parseJSONCookie = function(str) {
if (0 == str.indexOf('j:')) {
try {
return JSON.parse(str.slice(2));
} catch (err) {
// no op
}
}
};
/**
* Pause `data` and `end` events on the given `obj`.
* Middleware performing async tasks _should_ utilize
* this utility (or similar), to re-emit data once
* the async operation has completed, otherwise these
* events may be lost. Pause is only required for
* node versions less than 10, and is replaced with
* noop's otherwise.
*
* var pause = utils.pause(req);
* fs.readFile(path, function(){
* next();
* pause.resume();
* });
*
* @param {Object} obj
* @return {Object}
* @api private
*/
exports.pause = exports.brokenPause
? require('pause')
: function () {
return {
end: noop,
resume: noop
}
}
/**
* Strip `Content-*` headers from `res`.
*
* @param {ServerResponse} res
* @api private
*/
exports.removeContentHeaders = function(res){
if (!res._headers) return;
Object.keys(res._headers).forEach(function(field){
if (0 == field.indexOf('content')) {
res.removeHeader(field);
}
});
};
exports.removeContentHeaders = exports.deprecate(exports.removeContentHeaders,
'utils.removeContentHeaders: this private api moved with serve-static');
/**
* Check if `req` is a conditional GET request.
*
* @param {IncomingMessage} req
* @return {Boolean}
* @api private
*/
exports.conditionalGET = function(req) {
return req.headers['if-modified-since']
|| req.headers['if-none-match'];
};
exports.conditionalGET = exports.deprecate(exports.conditionalGET,
'utils.conditionalGET: use fresh module directly');
/**
* Respond with 401 "Unauthorized".
*
* @param {ServerResponse} res
* @param {String} realm
* @api private
*/
exports.unauthorized = function(res, realm) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"');
res.end('Unauthorized');
};
exports.unauthorized = exports.deprecate(exports.unauthorized,
'utils.unauthorized: this private api moved with basic-auth-connect');
/**
* Respond with 304 "Not Modified".
*
* @param {ServerResponse} res
* @param {Object} headers
* @api private
*/
exports.notModified = function(res) {
exports.removeContentHeaders(res);
res.statusCode = 304;
res.end();
};
exports.notModified = exports.deprecate(exports.notModified,
'utils.notModified: this private api moved with serve-static');
/**
* Return an ETag in the form of `"<size>-<mtime>"`
* from the given `stat`.
*
* @param {Object} stat
* @return {String}
* @api private
*/
exports.etag = function(stat) {
return '"' + stat.size + '-' + Number(stat.mtime) + '"';
};
exports.etag = exports.deprecate(exports.etag,
'utils.etag: this private api moved with serve-static');
/**
* Parse the given Cache-Control `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
exports.parseCacheControl = function(str){
var directives = str.split(',')
, obj = {};
for(var i = 0, len = directives.length; i < len; i++) {
var parts = directives[i].split('=')
, key = parts.shift().trim()
, val = parseInt(parts.shift(), 10);
obj[key] = isNaN(val) ? true : val;
}
return obj;
};
/**
* Parse the `req` url with memoization.
*
* @param {ServerRequest} req
* @return {Object}
* @api private
*/
exports.parseUrl = exports.deprecate(parseurl,
'utils.parseUrl: use parseurl module directly');
/**
* Parse byte `size` string.
*
* @param {String} size
* @return {Number}
* @api private
*/
exports.parseBytes = require('bytes');
exports.parseBytes = exports.deprecate(exports.parseBytes,
'utils.parseBytes: use bytes module directly');
/**
* Normalizes the path separator from system separator
* to URL separator, aka `/`.
*
* @param {String} path
* @return {String}
* @api private
*/
exports.normalizeSlashes = function normalizeSlashes(path) {
return path.split(sep).join('/');
};
exports.normalizeSlashes = exports.deprecate(exports.normalizeSlashes,
'utils.normalizeSlashes: this private api moved with serve-index');
/**
* Set the charset in a given Content-Type string if none exists.
*
* @param {String} type
* @param {String} charset
* @return {String}
* @api private
*/
exports.setCharset = function(type, charset){
if (!type || !charset) return type;
var exists = charsetRegExp.test(type);
// keep existing charset
if (exists) {
return type;
}
return type + '; charset=' + charset;
};
function noop() {}

@ -0,0 +1,8 @@
BIN = ./node_modules/.bin/
test:
@NODE_ENV=test $(BIN)mocha \
--require should \
--reporter spec
.PHONY: test

@ -0,0 +1,60 @@
# simgr - Simple Image Resizer [![Build Status](https://travis-ci.org/expressjs/basic-auth-connect.png)](https://travis-ci.org/expressjs/basic-auth-connect)
Connect's Basic Auth middleware in its own module. This module is considered deprecated. You should instead create your own middleware with [basic-auth](https://github.com/visionmedia/node-basic-auth).
## API
```js
var basicAuth = require('basic-auth-connect');
```
Sorry, couldn't think of a more clever name.
Simple username and password
```js
connect()
.use(basicAuth('username', 'password'));
```
Callback verification
```js
connect()
.use(basicAuth(function(user, pass){
return 'tj' == user && 'wahoo' == pass;
}))
```
Async callback verification, accepting `fn(err, user)`.
```
connect()
.use(basicAuth(function(user, pass, fn){
User.authenticate({ user: user, pass: pass }, fn);
}))
```
## License
The MIT License (MIT)
Copyright (c) 2013 Jonathan Ong me@jongleberry.com
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.

@ -0,0 +1,128 @@
var http = require('http');
/*!
* Connect - basicAuth
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Basic Auth:
*
* Status: Deprecated. No bug reports or pull requests are welcomed
* for this middleware. However, this middleware will not be removed.
* Instead, you should use [basic-auth](https://github.com/visionmedia/node-basic-auth).
*
* Enfore basic authentication by providing a `callback(user, pass)`,
* which must return `true` in order to gain access. Alternatively an async
* method is provided as well, invoking `callback(user, pass, callback)`. Populates
* `req.user`. The final alternative is simply passing username / password
* strings.
*
* Simple username and password
*
* connect(connect.basicAuth('username', 'password'));
*
* Callback verification
*
* connect()
* .use(connect.basicAuth(function(user, pass){
* return 'tj' == user && 'wahoo' == pass;
* }))
*
* Async callback verification, accepting `fn(err, user)`.
*
* connect()
* .use(connect.basicAuth(function(user, pass, fn){
* User.authenticate({ user: user, pass: pass }, fn);
* }))
*
* @param {Function|String} callback or username
* @param {String} realm
* @api public
*/
module.exports = function basicAuth(callback, realm) {
var username, password;
// user / pass strings
if ('string' == typeof callback) {
username = callback;
password = realm;
if ('string' != typeof password) throw new Error('password argument required');
realm = arguments[2];
callback = function(user, pass){
return user == username && pass == password;
}
}
realm = realm || 'Authorization Required';
return function(req, res, next) {
var authorization = req.headers.authorization;
if (req.user) return next();
if (!authorization) return unauthorized(res, realm);
var parts = authorization.split(' ');
if (parts.length !== 2) return next(error(400));
var scheme = parts[0]
, credentials = new Buffer(parts[1], 'base64').toString()
, index = credentials.indexOf(':');
if ('Basic' != scheme || index < 0) return next(error(400));
var user = credentials.slice(0, index)
, pass = credentials.slice(index + 1);
// async
if (callback.length >= 3) {
callback(user, pass, function(err, user){
if (err || !user) return unauthorized(res, realm);
req.user = req.remoteUser = user;
next();
});
// sync
} else {
if (callback(user, pass)) {
req.user = req.remoteUser = user;
next();
} else {
unauthorized(res, realm);
}
}
}
};
/**
* Respond with 401 "Unauthorized".
*
* @param {ServerResponse} res
* @param {String} realm
* @api private
*/
function unauthorized(res, realm) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"');
res.end('Unauthorized');
};
/**
* Generate an `Error` from the given status `code`
* and optional `msg`.
*
* @param {Number} code
* @param {String} msg
* @return {Error}
* @api private
*/
function error(code, msg){
var err = new Error(msg || http.STATUS_CODES[code]);
err.status = code;
return err;
};

@ -0,0 +1,34 @@
{
"name": "basic-auth-connect",
"description": "Basic auth middleware for node and connect",
"version": "1.0.0",
"author": {
"name": "Jonathan Ong",
"email": "me@jongleberry.com",
"url": "http://jongleberry.com"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/expressjs/basic-auth-connect.git"
},
"bugs": {
"url": "https://github.com/expressjs/basic-auth-connect/issues"
},
"devDependencies": {
"mocha": "*",
"should": "*",
"supertest": "*",
"connect": "*"
},
"scripts": {
"test": "make test"
},
"readme": "# simgr - Simple Image Resizer [![Build Status](https://travis-ci.org/expressjs/basic-auth-connect.png)](https://travis-ci.org/expressjs/basic-auth-connect)\n\nConnect's Basic Auth middleware in its own module. This module is considered deprecated. You should instead create your own middleware with [basic-auth](https://github.com/visionmedia/node-basic-auth).\n\n## API\n\n```js\nvar basicAuth = require('basic-auth-connect');\n```\n\nSorry, couldn't think of a more clever name.\n\nSimple username and password\n\n```js\nconnect()\n.use(basicAuth('username', 'password'));\n```\n\nCallback verification\n\n```js\nconnect()\n.use(basicAuth(function(user, pass){\n return 'tj' == user && 'wahoo' == pass;\n}))\n```\n\nAsync callback verification, accepting `fn(err, user)`.\n\n```\nconnect()\n.use(basicAuth(function(user, pass, fn){\n User.authenticate({ user: user, pass: pass }, fn);\n}))\n```\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2013 Jonathan Ong me@jongleberry.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.",
"readmeFilename": "README.md",
"homepage": "https://github.com/expressjs/basic-auth-connect",
"_id": "basic-auth-connect@1.0.0",
"_shasum": "fdb0b43962ca7b40456a7c2bb48fe173da2d2122",
"_from": "basic-auth-connect@1.0.0",
"_resolved": "https://registry.npmjs.org/basic-auth-connect/-/basic-auth-connect-1.0.0.tgz"
}

@ -0,0 +1,57 @@
1.3.1 / 2014-06-11
==================
* deps: type-is@1.2.1
- Switch dependency from mime to mime-types@1.0.0
1.3.0 / 2014-05-31
==================
* add `extended` option to urlencoded parser
1.2.2 / 2014-05-27
==================
* deps: raw-body@1.1.6
- assert stream encoding on node.js 0.8
- assert stream encoding on node.js < 0.10.6
- deps: bytes@1
1.2.1 / 2014-05-26
==================
* invoke `next(err)` after request fully read
- prevents hung responses and socket hang ups
1.2.0 / 2014-05-11
==================
* add `verify` option
* deps: type-is@1.2.0
- support suffix matching
1.1.2 / 2014-05-11
==================
* improve json parser speed
1.1.1 / 2014-05-11
==================
* fix repeated limit parsing with every request
1.1.0 / 2014-05-10
==================
* add `type` option
* deps: pin for safety and consistency
1.0.2 / 2014-04-14
==================
* use `type-is` module
1.0.1 / 2014-03-20
==================
* lower default limits to 100kb

@ -0,0 +1,113 @@
# body-parser
[![NPM version](https://badge.fury.io/js/body-parser.svg)](https://badge.fury.io/js/body-parser)
[![Build Status](https://travis-ci.org/expressjs/body-parser.svg?branch=master)](https://travis-ci.org/expressjs/body-parser)
[![Coverage Status](https://img.shields.io/coveralls/expressjs/body-parser.svg?branch=master)](https://coveralls.io/r/expressjs/body-parser)
Node.js body parsing middleware.
This only handles `urlencoded` and `json` bodies.
For multipart bodies, you may be interested in the following modules:
- [busboy](https://www.npmjs.org/package/busboy#readme) and [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme)
- [multiparty](https://www.npmjs.org/package/multiparty#readme) and [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme)
- [formidable](https://www.npmjs.org/package/formidable#readme)
- [multer](https://www.npmjs.org/package/multer#readme)
Other body parsers you might be interested in:
- [body](https://www.npmjs.org/package/body#readme)
- [co-body](https://www.npmjs.org/package/co-body#readme)
## Installation
```sh
$ npm install body-parser
```
## API
```js
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded())
// parse application/json
app.use(bodyParser.json())
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
app.use(function (req, res, next) {
console.log(req.body) // populated!
next()
})
```
### bodyParser(options)
Returns middleware that parses both `json` and `urlencoded`.
The `options` are passed to both middleware, except `type`.
### bodyParser.json(options)
Returns middleware that only parses `json`. The options are:
- `strict` - only parse objects and arrays. (default: `true`)
- `limit` - maximum request body size. (default: `<100kb>`)
- `reviver` - passed to `JSON.parse()`
- `type` - request content-type to parse (default: `json`)
- `verify` - function to verify body content
The `type` argument is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library. This can be an extension name (like `json`), a mime type (like `application/json`), or a mime time with a wildcard (like `*/json`).
The `verify` argument, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error.
The `reviver` argument is passed directly to `JSON.parse` as the second argument. You can find more information on this argument [in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).
### bodyParser.urlencoded(options)
Returns middleware that only parses `urlencoded` bodies. The options are:
- `extended` - parse extended syntax with the [qs](https://www.npmjs.org/package/qs#readme) module. (default: `true`)
- `limit` - maximum request body size. (default: `<100kb>`)
- `type` - request content-type to parse (default: `urlencoded`)
- `verify` - function to verify body content
The `extended` argument allows to choose between parsing the urlencoded data with the `querystring` library (when `false`) or the `qs` library (when `true`). The "extended" syntax allows for rich objects and arrays to be encoded into the urlencoded format, allowing for a JSON-like exterience with urlencoded. For more information, please [see the qs library](https://www.npmjs.org/package/qs#readme).
The `type` argument is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library. This can be an extension name (like `urlencoded`), a mime type (like `application/x-www-form-urlencoded`), or a mime time with a wildcard (like `*/x-www-form-urlencoded`).
The `verify` argument, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error.
### req.body
A new `body` object containing the parsed data is populated on the `request` object after the middleware.
## License
The MIT License (MIT)
Copyright (c) 2014 Jonathan Ong me@jongleberry.com
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.

@ -0,0 +1,195 @@
var bytes = require('bytes');
var getBody = require('raw-body');
var typeis = require('type-is');
var qs = require('qs');
var querystring = require('querystring');
var firstcharRegExp = /^\s*(.)/
exports = module.exports = bodyParser;
exports.json = json;
exports.urlencoded = urlencoded;
function bodyParser(options){
var opts = {}
options = options || {}
// exclude type option
for (var prop in options) {
if ('type' !== prop) {
opts[prop] = options[prop]
}
}
var _urlencoded = urlencoded(opts)
var _json = json(opts)
return function bodyParser(req, res, next) {
_json(req, res, function(err){
if (err) return next(err);
_urlencoded(req, res, next);
});
}
}
function json(options){
options = options || {};
var limit = typeof options.limit !== 'number'
? bytes(options.limit || '100kb')
: options.limit;
var reviver = options.reviver
var strict = options.strict !== false;
var type = options.type || 'json';
var verify = options.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
function parse(str) {
if (0 === str.length) {
throw new Error('invalid json, empty body')
}
if (strict) {
var first = firstchar(str)
if (first !== '{' && first !== '[') {
throw new Error('invalid json')
}
}
return JSON.parse(str, reviver)
}
return function jsonParser(req, res, next) {
if (req._body) return next();
req.body = req.body || {}
if (!typeis(req, type)) return next();
// read
read(req, res, next, parse, {
limit: limit,
verify: verify
})
}
}
function urlencoded(options){
options = options || {};
var extended = options.extended !== false
var limit = typeof options.limit !== 'number'
? bytes(options.limit || '100kb')
: options.limit;
var type = options.type || 'urlencoded';
var verify = options.verify || false;
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
var queryparse = extended
? qs.parse
: querystring.parse
function parse(str) {
return str.length
? queryparse(str)
: {}
}
return function urlencodedParser(req, res, next) {
if (req._body) return next();
req.body = req.body || {}
if (!typeis(req, type)) return next();
// read
read(req, res, next, parse, {
limit: limit,
verify: verify
})
}
}
function firstchar(str) {
if (!str) return ''
var match = firstcharRegExp.exec(str)
return match ? match[1] : ''
}
function read(req, res, next, parse, options) {
var length = req.headers['content-length']
var waitend = true
// flag as parsed
req._body = true
options = options || {}
options.length = length
var encoding = options.encoding || 'utf-8'
var verify = options.verify
options.encoding = verify
? null
: encoding
req.on('aborted', cleanup)
req.on('end', cleanup)
req.on('error', cleanup)
// read body
getBody(req, options, function (err, body) {
if (err && waitend && req.readable) {
// read off entire request
req.resume()
req.once('end', function onEnd() {
next(err)
})
return
}
if (err) {
next(err)
return
}
var str
// verify
if (verify) {
try {
verify(req, res, body, encoding)
} catch (err) {
if (!err.status) err.status = 403
return next(err)
}
}
// parse
try {
str = typeof body !== 'string'
? body.toString(encoding)
: body
req.body = parse(str)
} catch (err){
err.body = str
err.status = 400
return next(err)
}
next()
})
function cleanup() {
waitend = false
req.removeListener('aborted', cleanup)
req.removeListener('end', cleanup)
req.removeListener('error', cleanup)
}
}

@ -0,0 +1,14 @@
NODE ?= node
BIN = ./node_modules/.bin/
test:
@${NODE} ${BIN}mocha \
--harmony-generators \
--reporter spec \
--bail \
./test/index.js
clean:
@rm -rf node_modules
.PHONY: test clean

@ -0,0 +1,96 @@
# Raw Body [![Build Status](https://travis-ci.org/stream-utils/raw-body.svg?branch=master)](https://travis-ci.org/stream-utils/raw-body)
Gets the entire buffer of a stream either as a `Buffer` or a string.
Validates the stream's length against an expected length and maximum limit.
Ideal for parsing request bodies.
## API
```js
var getRawBody = require('raw-body')
app.use(function (req, res, next) {
getRawBody(req, {
length: req.headers['content-length'],
limit: '1mb',
encoding: 'utf8'
}, function (err, string) {
if (err)
return next(err)
req.text = string
next()
})
})
```
or in a Koa generator:
```js
app.use(function* (next) {
var string = yield getRawBody(this.req, {
length: this.length,
limit: '1mb',
encoding: 'utf8'
})
})
```
### getRawBody(stream, [options], [callback])
Returns a thunk for yielding with generators.
Options:
- `length` - The length length of the stream.
If the contents of the stream do not add up to this length,
an `400` error code is returned.
- `limit` - The byte limit of the body.
If the body ends up being larger than this limit,
a `413` error code is returned.
- `encoding` - The requested encoding.
By default, a `Buffer` instance will be returned.
Most likely, you want `utf8`.
You can use any type of encoding supported by [StringDecoder](http://nodejs.org/api/string_decoder.html).
You can also pass `true` which sets it to the default `utf8`
`callback(err, res)`:
- `err` - the following attributes will be defined if applicable:
- `limit` - the limit in bytes
- `length` and `expected` - the expected length of the stream
- `received` - the received bytes
- `status` and `statusCode` - the corresponding status code for the error
- `type` - either `entity.too.large`, `request.size.invalid`, or `stream.encoding.set`
- `res` - the result, either as a `String` if an encoding was set or a `Buffer` otherwise.
If an error occurs, the stream will be paused,
and you are responsible for correctly disposing the stream.
For HTTP requests, no handling is required if you send a response.
For streams that use file descriptors, you should `stream.destroy()` or `stream.close()` to prevent leaks.
## License
The MIT License (MIT)
Copyright (c) 2013 Jonathan Ong me@jongleberry.com
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.

@ -0,0 +1,168 @@
var StringDecoder = require('string_decoder').StringDecoder
var bytes = require('bytes')
module.exports = function (stream, options, done) {
if (typeof options === 'function') {
done = options
options = {}
} else if (!options) {
options = {}
} else if (options === true) {
options = {
encoding: 'utf8'
}
}
// convert the limit to an integer
var limit = null
if (typeof options.limit === 'number')
limit = options.limit
if (typeof options.limit === 'string')
limit = bytes(options.limit)
// convert the expected length to an integer
var length = null
if (options.length != null && !isNaN(options.length))
length = parseInt(options.length, 10)
// check the length and limit options.
// note: we intentionally leave the stream paused,
// so users should handle the stream themselves.
if (limit !== null && length !== null && length > limit) {
if (typeof stream.pause === 'function')
stream.pause()
process.nextTick(function () {
var err = makeError('request entity too large', 'entity.too.large')
err.status = err.statusCode = 413
err.length = err.expected = length
err.limit = limit
done(err)
})
return defer
}
// streams1: assert request encoding is buffer.
// streams2+: assert the stream encoding is buffer.
// stream._decoder: streams1
// state.encoding: streams2
// state.decoder: streams2, specifically < 0.10.6
var state = stream._readableState
if (stream._decoder || (state && (state.encoding || state.decoder))) {
if (typeof stream.pause === 'function')
stream.pause()
process.nextTick(function () {
var err = makeError('stream encoding should not be set',
'stream.encoding.set')
// developer error
err.status = err.statusCode = 500
done(err)
})
return defer
}
var received = 0
// note: we delegate any invalid encodings to the constructor
var decoder = options.encoding
? new StringDecoder(options.encoding === true ? 'utf8' : options.encoding)
: null
var buffer = decoder
? ''
: []
stream.on('data', onData)
stream.once('end', onEnd)
stream.once('error', onEnd)
stream.once('close', cleanup)
return defer
// yieldable support
function defer(fn) {
done = fn
}
function onData(chunk) {
received += chunk.length
decoder
? buffer += decoder.write(chunk)
: buffer.push(chunk)
if (limit !== null && received > limit) {
if (typeof stream.pause === 'function')
stream.pause()
var err = makeError('request entity too large', 'entity.too.large')
err.status = err.statusCode = 413
err.received = received
err.limit = limit
done(err)
cleanup()
}
}
function onEnd(err) {
if (err) {
if (typeof stream.pause === 'function')
stream.pause()
done(err)
} else if (length !== null && received !== length) {
err = makeError('request size did not match content length',
'request.size.invalid')
err.status = err.statusCode = 400
err.received = received
err.length = err.expected = length
done(err)
} else {
done(null, decoder
? buffer + endStringDecoder(decoder)
: Buffer.concat(buffer)
)
}
cleanup()
}
function cleanup() {
received = buffer = null
stream.removeListener('data', onData)
stream.removeListener('end', onEnd)
stream.removeListener('error', onEnd)
stream.removeListener('close', cleanup)
}
}
// to create serializable errors you must re-set message so
// that it is enumerable and you must re configure the type
// property so that is writable and enumerable
function makeError(message, type) {
var error = new Error()
error.message = message
Object.defineProperty(error, 'type', {
value: type,
enumerable: true,
writable: true,
configurable: true
})
return error
}
// https://github.com/Raynos/body/blob/2512ced39e31776e5a2f7492b907330badac3a40/index.js#L72
// bug fix for missing `StringDecoder.end` in v0.8.x
function endStringDecoder(decoder) {
if (decoder.end) {
return decoder.end()
}
var res = ""
if (decoder.charReceived) {
var cr = decoder.charReceived
var buf = decoder.charBuffer
var enc = decoder.encoding
res += buf.slice(0, cr).toString(enc)
}
return res
}

@ -0,0 +1,43 @@
{
"name": "raw-body",
"description": "Get and validate the raw body of a readable stream.",
"version": "1.1.6",
"author": {
"name": "Jonathan Ong",
"email": "me@jongleberry.com",
"url": "http://jongleberry.com"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/stream-utils/raw-body.git"
},
"bugs": {
"url": "https://github.com/stream-utils/raw-body/issues"
},
"dependencies": {
"bytes": "1"
},
"devDependencies": {
"readable-stream": "~1.0.17",
"co": "3",
"gnode": "~0.0.4",
"mocha": "^1.14.0",
"through2": "~0.4.1",
"request": "^2.27.0",
"assert-tap": "~0.1.4"
},
"scripts": {
"test": "NODE=gnode make test && node ./test/acceptance.js"
},
"engines": {
"node": ">= 0.8.0"
},
"readme": "# Raw Body [![Build Status](https://travis-ci.org/stream-utils/raw-body.svg?branch=master)](https://travis-ci.org/stream-utils/raw-body)\n\nGets the entire buffer of a stream either as a `Buffer` or a string.\nValidates the stream's length against an expected length and maximum limit.\nIdeal for parsing request bodies.\n\n## API\n\n```js\nvar getRawBody = require('raw-body')\n\napp.use(function (req, res, next) {\n getRawBody(req, {\n length: req.headers['content-length'],\n limit: '1mb',\n encoding: 'utf8'\n }, function (err, string) {\n if (err)\n return next(err)\n\n req.text = string\n next()\n })\n})\n```\n\nor in a Koa generator:\n\n```js\napp.use(function* (next) {\n var string = yield getRawBody(this.req, {\n length: this.length,\n limit: '1mb',\n encoding: 'utf8'\n })\n})\n```\n\n### getRawBody(stream, [options], [callback])\n\nReturns a thunk for yielding with generators.\n\nOptions:\n\n- `length` - The length length of the stream.\n If the contents of the stream do not add up to this length,\n an `400` error code is returned.\n- `limit` - The byte limit of the body.\n If the body ends up being larger than this limit,\n a `413` error code is returned.\n- `encoding` - The requested encoding.\n By default, a `Buffer` instance will be returned.\n Most likely, you want `utf8`.\n You can use any type of encoding supported by [StringDecoder](http://nodejs.org/api/string_decoder.html).\n You can also pass `true` which sets it to the default `utf8`\n\n`callback(err, res)`:\n\n- `err` - the following attributes will be defined if applicable:\n\n - `limit` - the limit in bytes\n - `length` and `expected` - the expected length of the stream\n - `received` - the received bytes\n - `status` and `statusCode` - the corresponding status code for the error\n - `type` - either `entity.too.large`, `request.size.invalid`, or `stream.encoding.set`\n\n- `res` - the result, either as a `String` if an encoding was set or a `Buffer` otherwise.\n\nIf an error occurs, the stream will be paused,\nand you are responsible for correctly disposing the stream.\nFor HTTP requests, no handling is required if you send a response.\nFor streams that use file descriptors, you should `stream.destroy()` or `stream.close()` to prevent leaks.\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2013 Jonathan Ong me@jongleberry.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n",
"readmeFilename": "README.md",
"homepage": "https://github.com/stream-utils/raw-body",
"_id": "raw-body@1.1.6",
"_shasum": "98e9df9a7e2df994931b7cdb4b2a6b9694a74f02",
"_from": "raw-body@1.1.6",
"_resolved": "https://registry.npmjs.org/raw-body/-/raw-body-1.1.6.tgz"
}

File diff suppressed because one or more lines are too long

@ -0,0 +1,25 @@
1.0.0 / 2014-05-05
==================
* add negative support. fixes #6
0.3.0 / 2014-03-19
==================
* added terabyte support
0.2.1 / 2013-04-01
==================
* add .component
0.2.0 / 2012-10-28
==================
* bytes(200).should.eql('200b')
0.1.0 / 2012-07-04
==================
* add bytes to string conversion [yields]

@ -0,0 +1,7 @@
test:
@./node_modules/.bin/mocha \
--reporter spec \
--require should
.PHONY: test

@ -0,0 +1,54 @@
# node-bytes
Byte string parser / formatter.
## Example:
```js
bytes('1kb')
// => 1024
bytes('2mb')
// => 2097152
bytes('1gb')
// => 1073741824
bytes(1073741824)
// => 1gb
bytes(1099511627776)
// => 1tb
```
## Installation
```
$ npm install bytes
$ component install visionmedia/bytes.js
```
## License
(The MIT License)
Copyright (c) 2012 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
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.

@ -0,0 +1,7 @@
{
"name": "bytes",
"description": "byte size string parser / serializer",
"keywords": ["bytes", "utility"],
"version": "0.2.1",
"scripts": ["index.js"]
}

@ -0,0 +1,41 @@
/**
* Parse byte `size` string.
*
* @param {String} size
* @return {Number}
* @api public
*/
module.exports = function(size) {
if ('number' == typeof size) return convert(size);
var parts = size.match(/^(\d+(?:\.\d+)?) *(kb|mb|gb|tb)$/)
, n = parseFloat(parts[1])
, type = parts[2];
var map = {
kb: 1 << 10
, mb: 1 << 20
, gb: 1 << 30
, tb: ((1 << 30) * 1024)
};
return map[type] * n;
};
/**
* convert bytes into string.
*
* @param {Number} b - bytes to convert
* @return {String}
* @api public
*/
function convert (b) {
var tb = ((1 << 30) * 1024), gb = 1 << 30, mb = 1 << 20, kb = 1 << 10, abs = Math.abs(b);
if (abs >= tb) return (Math.round(b / tb * 100) / 100) + 'tb';
if (abs >= gb) return (Math.round(b / gb * 100) / 100) + 'gb';
if (abs >= mb) return (Math.round(b / mb * 100) / 100) + 'mb';
if (abs >= kb) return (Math.round(b / kb * 100) / 100) + 'kb';
return b + 'b';
}

@ -0,0 +1,35 @@
{
"name": "bytes",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca",
"url": "http://tjholowaychuk.com"
},
"description": "byte size string parser / serializer",
"repository": {
"type": "git",
"url": "https://github.com/visionmedia/bytes.js.git"
},
"version": "1.0.0",
"main": "index.js",
"dependencies": {},
"devDependencies": {
"mocha": "*",
"should": "*"
},
"component": {
"scripts": {
"bytes/index.js": "index.js"
}
},
"readme": "# node-bytes\n\n Byte string parser / formatter.\n\n## Example:\n\n```js\nbytes('1kb')\n// => 1024\n\nbytes('2mb')\n// => 2097152\n\nbytes('1gb')\n// => 1073741824\n\nbytes(1073741824)\n// => 1gb\n\nbytes(1099511627776)\n// => 1tb\n```\n\n## Installation\n\n```\n$ npm install bytes\n$ component install visionmedia/bytes.js\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk &lt;tj@vision-media.ca&gt;\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\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 OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n",
"readmeFilename": "Readme.md",
"bugs": {
"url": "https://github.com/visionmedia/bytes.js/issues"
},
"homepage": "https://github.com/visionmedia/bytes.js",
"_id": "bytes@1.0.0",
"_shasum": "3569ede8ba34315fab99c3e92cb04c7220de1fa8",
"_from": "bytes@1.0.0",
"_resolved": "https://registry.npmjs.org/bytes/-/bytes-1.0.0.tgz"
}

@ -0,0 +1,47 @@
1.0.7 / 2014-06-11
==================
* use vary module for better `Vary` behavior
* deps: accepts@1.0.3
* deps: compressible@1.1.0
1.0.6 / 2014-06-03
==================
* fix regression when negotiation fails
1.0.5 / 2014-06-03
==================
* fix listeners for delayed stream creation
- fixes regression for certain `stream.pipe(res)` situations
1.0.4 / 2014-06-03
==================
* fix adding `Vary` when value stored as array
* fix back-pressure behavior
* fix length check for `res.end`
1.0.3 / 2014-05-29
==================
* use `accepts` for negotiation
* use `on-headers` to handle header checking
* deps: bytes@1.0.0
1.0.2 / 2014-04-29
==================
* only version compatible with node.js 0.8
* support headers given to `res.writeHead`
* deps: bytes@0.3.0
* deps: negotiator@0.4.3
1.0.1 / 2014-03-08
==================
* bump negotiator
* use compressible
* use .headersSent (drops 0.8 support)
* handle identity;q=0 case

@ -0,0 +1,58 @@
# compression
[![NPM version](https://badge.fury.io/js/compression.svg)](http://badge.fury.io/js/compression)
[![Build Status](https://travis-ci.org/expressjs/compression.svg?branch=master)](https://travis-ci.org/expressjs/compression)
[![Coverage Status](https://img.shields.io/coveralls/expressjs/compression.svg?branch=master)](https://coveralls.io/r/expressjs/compression)
Node.js compression middleware.
## API
```js
var express = require('express')
var compression = require('compression')
var app = express()
app.use(compression())
```
### compression(options)
Returns the compression middleware using the given `options`.
```js
app.use(compression({
threshold: 512
}))
```
#### Options
- `threshold` `<1kb>` - response is only compressed if the byte size is at or above this threshold.
- `filter` - a filtering callback function. Uses [Compressible](https://github.com/expressjs/compressible) by default.
In addition to these, [zlib](http://nodejs.org/api/zlib.html) options may be passed in to the options object.
## License
The MIT License (MIT)
Copyright (c) 2014 Jonathan Ong me@jongleberry.com
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.

@ -0,0 +1,199 @@
/*!
* compression
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var zlib = require('zlib');
var accepts = require('accepts');
var bytes = require('bytes');
var onHeaders = require('on-headers');
var compressible = require('compressible');
var vary = require('vary');
/**
* Supported content-encoding methods.
*/
exports.methods = {
gzip: zlib.createGzip
, deflate: zlib.createDeflate
};
/**
* Default filter function.
*/
exports.filter = function(req, res){
return compressible(res.getHeader('Content-Type'));
};
/**
* Compress response data with gzip / deflate.
*
* See README.md for documentation of options.
*
* @param {Object} options
* @return {Function} middleware
* @api public
*/
module.exports = function compression(options) {
options = options || {};
var filter = options.filter || exports.filter;
var threshold;
if (false === options.threshold || 0 === options.threshold) {
threshold = 0
} else if ('string' === typeof options.threshold) {
threshold = bytes(options.threshold)
} else {
threshold = options.threshold || 1024
}
return function compression(req, res, next){
var compress = true
var listeners = []
var write = res.write
var on = res.on
var end = res.end
var stream
// see #8
req.on('close', function(){
res.write = res.end = function(){};
});
// flush is noop by default
res.flush = noop;
// proxy
res.write = function(chunk, encoding){
if (!this._header) {
// if content-length is set and is lower
// than the threshold, don't compress
var length = res.getHeader('content-length');
if (!isNaN(length) && length < threshold) compress = false;
this._implicitHeader();
}
return stream
? stream.write(new Buffer(chunk, encoding))
: write.call(res, chunk, encoding);
};
res.end = function(chunk, encoding){
var len
if (chunk) {
len = Buffer.isBuffer(chunk)
? chunk.length
: Buffer.byteLength(chunk, encoding)
}
if (!this._header) {
compress = len && len >= threshold
}
if (chunk) {
this.write(chunk, encoding);
}
return stream
? stream.end()
: end.call(res);
};
res.on = function(type, listener){
if (!listeners || type !== 'drain') {
return on.call(this, type, listener)
}
if (stream) {
return stream.on(type, listener)
}
// buffer listeners for future stream
listeners.push([type, listener])
return this
}
function nocompress(){
addListeners(res, on, listeners)
listeners = null
}
onHeaders(res, function(){
// default request filter
if (!filter(req, res)) return nocompress()
// vary
vary(res, 'Accept-Encoding')
if (!compress) return nocompress()
var encoding = res.getHeader('Content-Encoding') || 'identity';
// already encoded
if ('identity' !== encoding) return nocompress()
// head
if ('HEAD' === req.method) return nocompress()
// compression method
var accept = accepts(req);
var method = accept.encodings(['gzip', 'deflate', 'identity']);
// negotiation failed
if (!method || method === 'identity') return nocompress()
// compression stream
stream = exports.methods[method](options);
addListeners(stream, stream.on, listeners)
// overwrite the flush method
res.flush = function(){
stream.flush();
}
// header fields
res.setHeader('Content-Encoding', method);
res.removeHeader('Content-Length');
// compression
stream.on('data', function(chunk){
if (write.call(res, chunk) === false) {
stream.pause()
}
});
stream.on('end', function(){
end.call(res);
});
on.call(res, 'drain', function() {
stream.resume()
});
});
next();
};
};
/**
* Add bufferred listeners to stream
*/
function addListeners(stream, on, listeners) {
for (var i = 0; i < listeners.length; i++) {
on.apply(stream, listeners[i])
}
}
function noop(){}

@ -0,0 +1,22 @@
1.0.3 / 2014-06-11
==================
* deps: negotiator@0.4.6
- Order by specificity when quality is the same
1.0.2 / 2014-05-29
==================
* Fix interpretation when header not in request
* deps: pin negotiator@0.4.5
1.0.1 / 2014-01-18
==================
* Identity encoding isn't always acceptable
* deps: negotiator@~0.4.0
1.0.0 / 2013-12-27
==================
* Genesis

@ -0,0 +1,101 @@
# Accepts
[![NPM version](https://badge.fury.io/js/accepts.svg)](http://badge.fury.io/js/accepts)
[![Build Status](https://travis-ci.org/expressjs/accepts.svg?branch=master)](https://travis-ci.org/expressjs/accepts)
[![Coverage Status](https://img.shields.io/coveralls/expressjs/accepts.svg?branch=master)](https://coveralls.io/r/expressjs/accepts)
Higher level content negotation based on [negotiator](https://github.com/federomero/negotiator). Extracted from [koa](https://github.com/koajs/koa) for general use.
In addition to negotatior, it allows:
- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` as well as `('text/html', 'application/json')`.
- Allows type shorthands such as `json`.
- Returns `false` when no types match
- Treats non-existent headers as `*`
## API
### var accept = new Accepts(req)
```js
var accepts = require('accepts')
http.createServer(function (req, res) {
var accept = accepts(req)
})
```
### accept\[property\]\(\)
Returns all the explicitly accepted content property as an array in descending priority.
- `accept.types()`
- `accept.encodings()`
- `accept.charsets()`
- `accept.languages()`
They are also aliased in singular form such as `accept.type()`. `accept.languages()` is also aliased as `accept.langs()`, etc.
Note: you should almost never do this in a real app as it defeats the purpose of content negotiation.
Example:
```js
// in Google Chrome
var encodings = accept.encodings() // -> ['sdch', 'gzip', 'deflate']
```
Since you probably don't support `sdch`, you should just supply the encodings you support:
```js
var encoding = accept.encodings('gzip', 'deflate') // -> 'gzip', probably
```
### accept\[property\]\(values, ...\)
You can either have `values` be an array or have an argument list of values.
If the client does not accept any `values`, `false` will be returned.
If the client accepts any `values`, the preferred `value` will be return.
For `accept.types()`, shorthand mime types are allowed.
Example:
```js
// req.headers.accept = 'application/json'
accept.types('json') // -> 'json'
accept.types('html', 'json') // -> 'json'
accept.types('html') // -> false
// req.headers.accept = ''
// which is equivalent to `*`
accept.types() // -> [], no explicit types
accept.types('text/html', 'text/json') // -> 'text/html', since it was first
```
## License
The MIT License (MIT)
Copyright (c) 2013 Jonathan Ong me@jongleberry.com
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.

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save