upgraded to express 3.x, converted jade templates, and worked out array notation for articles/exercises

This commit is contained in:
2013-01-17 16:12:44 -05:00
parent a899234e21
commit 3bab45fbad
326 changed files with 28430 additions and 5489 deletions

View File

@@ -3,15 +3,21 @@
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes');
var express = require('express');
http = require('http');
routes = require('./routes');
var async = require('async');
var app = module.exports = express.createServer();
//var app = module.exports = express.createServer();
var app = express();
var dbURL = 'mongodb://localhost/database';
var db = require('mongoose').connect(dbURL);
var qs = require('qs');
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
@@ -22,6 +28,10 @@ app.configure(function(){
secret: 'my secret string',
maxAge: 3600000
}));
app.use(function(req, res, next){
res.locals.session = req.session;
next();
});
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
@@ -41,6 +51,7 @@ require('./routes/users')(app);
require('./routes/session')(app);
require('./routes/articles')(app);
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
//http.listen(3000
http.createServer(app).listen(3000, function(){
console.log("Express server listening on port %d in %s mode");
});

15
test/node_modules/.bin/express generated vendored
View File

@@ -1,15 +0,0 @@
#!/bin/sh
basedir=`dirname "$0"`
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../express/bin/express" "$@"
ret=$?
else
node "$basedir/../express/bin/express" "$@"
ret=$?
fi
exit $ret

1
test/node_modules/.bin/express generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../express/bin/express

View File

@@ -5,3 +5,5 @@ support/
test/
testing.js
.DS_Store
coverage.html
lib-cov

3
test/node_modules/express/.travis.yml generated vendored Normal file
View File

@@ -0,0 +1,3 @@
language: node_js
node_js:
- 0.6

395
test/node_modules/express/History.md generated vendored
View File

@@ -1,64 +1,321 @@
2.5.11 / 2012-06-29
3.0.6 / 2013-01-04
==================
* Fixed backport of req.protocol
* add http verb methods to Router
* update connect
* fix mangling of the `res.cookie()` options object
* fix jsonp whitespace escape. Closes #1132
2.5.10 / 2012-06-15
3.0.5 / 2012-12-19
==================
* Remove annoying engines field from package.json
* Backport support for trusting X-Forwarded-Proto
* use version of `package.json` for `express` command
* add throwing when a non-function is passed to a route
* fix: explicitly remove Transfer-Encoding header from 204 and 304 responses
* revert "add 'etag' option"
2.5.9/ 2012-04-02
3.0.4 / 2012-12-05
==================
* add 'etag' option to disable `res.send()` Etags
* add escaping of urls in text/plain in `res.redirect()`
for old browsers interpreting as html
* change crc32 module for a more liberal license
* update connect
3.0.3 / 2012-11-13
==================
* update connect
* update cookie module
* fix cookie max-age
3.0.2 / 2012-11-08
==================
* add OPTIONS to cors example. Closes #1398
* fix route chaining regression. Closes #1397
3.0.1 / 2012-11-01
==================
* update connect
3.0.0 / 2012-10-23
==================
* add `make clean`
* add "Basic" check to req.auth
* add `req.auth` test coverage
* add cb && cb(payload) to `res.jsonp()`. Closes #1374
* add backwards compat for `res.redirect()` status. Closes #1336
* add support for `res.json()` to retain previously defined Content-Types. Closes #1349
* update connect
* change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382
* remove non-primitive string support for `res.send()`
* fix view-locals example. Closes #1370
* fix route-separation example
3.0.0rc5 / 2012-09-18
==================
* update connect
* add redis search example
* add static-files example
* add "x-powered-by" setting (`app.disable('x-powered-by')`)
* add "application/octet-stream" redirect Accept test case. Closes #1317
3.0.0rc4 / 2012-08-30
==================
* add `res.jsonp()`. Closes #1307
* add "verbose errors" option to error-pages example
* add another route example to express(1) so people are not so confused
* add redis online user activity tracking example
* update connect dep
* fix etag quoting. Closes #1310
* fix error-pages 404 status
* fix jsonp callback char restrictions
* remove old OPTIONS default response
3.0.0rc3 / 2012-08-13
==================
* update connect dep
* fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds]
* fix `res.render()` clobbering of "locals"
3.0.0rc2 / 2012-08-03
==================
* add CORS example
* update connect dep
* deprecate `.createServer()` & remove old stale examples
* fix: escape `res.redirect()` link
* fix vhost example
3.0.0rc1 / 2012-07-24
==================
* add more examples to view-locals
* add scheme-relative redirects (`res.redirect("//foo.com")`) support
* update cookie dep
* update connect dep
* update send dep
* fix `express(1)` -h flag, use -H for hogan. Closes #1245
* fix `res.sendfile()` socket error handling regression
3.0.0beta7 / 2012-07-16
==================
* update connect dep for `send()` root normalization regression
3.0.0beta6 / 2012-07-13
==================
* add `err.view` property for view errors. Closes #1226
* add "jsonp callback name" setting
* add support for "/foo/:bar*" non-greedy matches
* change `res.sendfile()` to use `send()` module
* change `res.send` to use "response-send" module
* remove `app.locals.use` and `res.locals.use`, use regular middleware
3.0.0beta5 / 2012-07-03
==================
* add "make check" support
* add route-map example
* add `res.json(obj, status)` support back for BC
* add "methods" dep, remove internal methods module
* update connect dep
* update auth example to utilize cores pbkdf2
* updated tests to use "supertest"
3.0.0beta4 / 2012-06-25
==================
* Added `req.auth`
* Added `req.range(size)`
* Added `res.links(obj)`
* Added `res.send(body, status)` support back for backwards compat
* Added `.default()` support to `res.format()`
* Added 2xx / 304 check to `req.fresh`
* Revert "Added + support to the router"
* Fixed `res.send()` freshness check, respect res.statusCode
3.0.0beta3 / 2012-06-15
==================
* Added hogan `--hjs` to express(1) [nullfirm]
* Added another example to content-negotiation
* Added `fresh` dep
* Changed: `res.send()` always checks freshness
* Fixed: expose connects mime module. Cloases #1165
3.0.0beta2 / 2012-06-06
==================
* Added `+` support to the router
* Added `req.host`
* Changed `req.param()` to check route first
* Update connect dep
3.0.0beta1 / 2012-06-01
==================
* Added `res.format()` callback to override default 406 behaviour
* Fixed `res.redirect()` 406. Closes #1154
3.0.0alpha5 / 2012-05-30
==================
* Added `req.ip`
* Added `{ signed: true }` option to `res.cookie()`
* Removed `res.signedCookie()`
* Changed: dont reverse `req.ips`
* Fixed "trust proxy" setting check for `req.ips`
3.0.0alpha4 / 2012-05-09
==================
* Added: allow `[]` in jsonp callback. Closes #1128
* Added `PORT` env var support in generated template. Closes #1118 [benatkin]
* Updated: connect 2.2.2
3.0.0alpha3 / 2012-05-04
==================
* Added public `app.routes`. Closes #887
* Added _view-locals_ example
* Added _mvc_ example
* Added `res.locals.use()`. Closes #1120
* Added conditional-GET support to `res.send()`
* Added: coerce `res.set()` values to strings
* Changed: moved `static()` in generated apps below router
* Changed: `res.send()` only set ETag when not previously set
* Changed connect 2.2.1 dep
* Changed: `make test` now runs unit / acceptance tests
* Fixed req/res proto inheritance
3.0.0alpha2 / 2012-04-26
==================
* Added `make benchmark` back
* Added `res.send()` support for `String` objects
* Added client-side data exposing example
* Added `res.header()` and `req.header()` aliases for BC
* Added `express.createServer()` for BC
* Perf: memoize parsed urls
* Perf: connect 2.2.0 dep
* Changed: make `expressInit()` middleware self-aware
* Fixed: use app.get() for all core settings
* Fixed redis session example
* Fixed session example. Closes #1105
* Fixed generated express dep. Closes #1078
3.0.0alpha1 / 2012-04-15
==================
* Added `app.locals.use(callback)`
* Added `app.locals` object
* Added `app.locals(obj)`
* Added `res.locals` object
* Added `res.locals(obj)`
* Added `res.format()` for content-negotiation
* Added `app.engine()`
* Added `res.cookie()` JSON cookie support
* Added "trust proxy" setting
* Added `req.subdomains`
* Added `req.protocol`
* Added `req.secure`
* Added `req.path`
* Added `req.ips`
* Added `req.fresh`
* Added `req.stale`
* Added comma-delmited / array support for `req.accepts()`
* Added debug instrumentation
* Added `res.set(obj)`
* Added `res.set(field, value)`
* Added `res.get(field)`
* Added `app.get(setting)`. Closes #842
* Added `req.acceptsLanguage()`
* Added `req.acceptsCharset()`
* Added `req.accepted`
* Added `req.acceptedLanguages`
* Added `req.acceptedCharsets`
* Added "json replacer" setting
* Added "json spaces" setting
* Added X-Forwarded-Proto support to `res.redirect()`. Closes #92
* Added `--less` support to express(1)
* Added `express.response` prototype
* Added `express.request` prototype
* Added `express.application` prototype
* Added `app.path()`
* Added `app.render()`
* Added `res.type()` to replace `res.contentType()`
* Changed: `res.redirect()` to add relative support
* Changed: enable "jsonp callback" by default
* Changed: renamed "case sensitive routes" to "case sensitive routing"
* Rewrite of all tests with mocha
* Removed "root" setting
* Removed `res.redirect('home')` support
* Removed `req.notify()`
* Removed `app.register()`
* Removed `app.redirect()`
* Removed `app.is()`
* Removed `app.helpers()`
* Removed `app.dynamicHelpers()`
* Fixed `res.sendfile()` with non-GET. Closes #723
* Fixed express(1) public dir for windows. Closes #866
2.5.9/ 2012-04-02
==================
* Added support for PURGE request method [pbuyle]
* Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki]
2.5.8 / 2012-02-08
2.5.8 / 2012-02-08
==================
* Update mkdirp dep. Closes #991
2.5.7 / 2012-02-06
2.5.7 / 2012-02-06
==================
* Fixed `app.all` duplicate DELETE requests [mscdex]
2.5.6 / 2012-01-13
2.5.6 / 2012-01-13
==================
* Updated hamljs dev dep. Closes #953
2.5.5 / 2012-01-08
2.5.5 / 2012-01-08
==================
* Fixed: set `filename` on cached templates [matthewleon]
2.5.4 / 2012-01-02
2.5.4 / 2012-01-02
==================
* Fixed `express(1)` eol on 0.4.x. Closes #947
2.5.3 / 2011-12-30
2.5.3 / 2011-12-30
==================
* Fixed `req.is()` when a charset is present
2.5.2 / 2011-12-10
2.5.2 / 2011-12-10
==================
* Fixed: express(1) LF -> CRLF for windows
2.5.1 / 2011-11-17
2.5.1 / 2011-11-17
==================
* Changed: updated connect to 1.8.x
* Removed sass.js support from express(1)
2.5.0 / 2011-10-24
2.5.0 / 2011-10-24
==================
* Added ./routes dir for generated app by default
@@ -67,7 +324,7 @@
* Removed `make test-cov` since it wont work with node 0.5.x
* Fixed express(1) public dir for windows. Closes #866
2.4.7 / 2011-10-05
2.4.7 / 2011-10-05
==================
* Added mkdirp to express(1). Closes #795
@@ -78,17 +335,17 @@
* Fixed `req.flash()`, only escape args
* Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie]
2.4.6 / 2011-08-22
2.4.6 / 2011-08-22
==================
* Fixed multiple param callback regression. Closes #824 [reported by TroyGoode]
2.4.5 / 2011-08-19
2.4.5 / 2011-08-19
==================
* Added support for routes to handle errors. Closes #809
* Added `app.routes.all()`. Closes #803
* Added "basepath" setting to work in conjunction with reverse proxies etc.
* Added "basepath" setting to work in conjunction with reverse proxies etc.
* Refactored `Route` to use a single array of callbacks
* Added support for multiple callbacks for `app.param()`. Closes #801
Closes #805
@@ -96,25 +353,25 @@ Closes #805
* Dependency: `qs >= 0.3.1`
* Fixed `res.redirect()` on windows due to `join()` usage. Closes #808
2.4.4 / 2011-08-05
2.4.4 / 2011-08-05
==================
* Fixed `res.header()` intention of a set, even when `undefined`
* Fixed `*`, value no longer required
* Fixed `res.send(204)` support. Closes #771
2.4.3 / 2011-07-14
2.4.3 / 2011-07-14
==================
* Added docs for `status` option special-case. Closes #739
* Fixed `options.filename`, exposing the view path to template engines
2.4.2. / 2011-07-06
2.4.2. / 2011-07-06
==================
* Revert "removed jsonp stripping" for XSS
2.4.1 / 2011-07-06
2.4.1 / 2011-07-06
==================
* Added `res.json()` JSONP support. Closes #737
@@ -126,14 +383,14 @@ Closes #805
* Changed; default cookie path to "home" setting. Closes #731
* Removed _pids/logs_ creation from express(1)
2.4.0 / 2011-06-28
2.4.0 / 2011-06-28
==================
* Added chainable `res.status(code)`
* Added `res.json()`, an explicit version of `res.send(obj)`
* Added simple web-service example
2.3.12 / 2011-06-22
2.3.12 / 2011-06-22
==================
* \#express is now on freenode! come join!
@@ -145,7 +402,7 @@ Closes #805
* Fixed view layout bug. Closes #720
* Fixed; ignore body on 304. Closes #701
2.3.11 / 2011-06-04
2.3.11 / 2011-06-04
==================
* Added `npm test`
@@ -153,14 +410,14 @@ Closes #805
* Fixed; `express(1)` adds express as a dep
* Fixed; prune on `prepublish`
2.3.10 / 2011-05-27
2.3.10 / 2011-05-27
==================
* Added `req.route`, exposing the current route
* Added _package.json_ generation support to `express(1)`
* Fixed call to `app.param()` function for optional params. Closes #682
2.3.9 / 2011-05-25
2.3.9 / 2011-05-25
==================
* Fixed bug-ish with `../' in `res.partial()` calls
@@ -179,7 +436,7 @@ Closes #805
* Removed module.parent check from express(1) generated app. Closes #670
* Refactored router. Closes #639
2.3.6 / 2011-05-20
2.3.6 / 2011-05-20
==================
* Changed; using devDependencies instead of git submodules
@@ -187,30 +444,30 @@ Closes #805
* Fixed markdown example
* Fixed view caching, should not be enabled in development
2.3.5 / 2011-05-20
2.3.5 / 2011-05-20
==================
* Added export `.view` as alias for `.View`
2.3.4 / 2011-05-08
2.3.4 / 2011-05-08
==================
* Added `./examples/say`
* Fixed `res.sendfile()` bug preventing the transfer of files with spaces
2.3.3 / 2011-05-03
2.3.3 / 2011-05-03
==================
* Added "case sensitive routes" option.
* Changed; split methods supported per rfc [slaskis]
* Fixed route-specific middleware when using the same callback function several times
2.3.2 / 2011-04-27
2.3.2 / 2011-04-27
==================
* Fixed view hints
2.3.1 / 2011-04-26
2.3.1 / 2011-04-26
==================
* Added `app.match()` as `app.match.all()`
@@ -220,7 +477,7 @@ Closes #805
* Fixed template caching collision issue. Closes #644
* Moved router over from connect and started refactor
2.3.0 / 2011-04-25
2.3.0 / 2011-04-25
==================
* Added options support to `res.clearCookie()`
@@ -229,18 +486,18 @@ Closes #805
* Changed; auto set Content-Type in res.attachement [Aaron Heckmann]
* Renamed "cache views" to "view cache". Closes #628
* Fixed caching of views when using several apps. Closes #637
* Fixed gotcha invoking `app.param()` callbacks once per route middleware.
* Fixed gotcha invoking `app.param()` callbacks once per route middleware.
Closes #638
* Fixed partial lookup precedence. Closes #631
Shaw]
2.2.2 / 2011-04-12
2.2.2 / 2011-04-12
==================
* Added second callback support for `res.download()` connection errors
* Fixed `filename` option passing to template engine
2.2.1 / 2011-04-04
2.2.1 / 2011-04-04
==================
* Added `layout(path)` helper to change the layout within a view. Closes #610
@@ -254,7 +511,7 @@ Shaw]
* Removed `request` and `response` locals
* Changed; errorHandler page title is now `Express` instead of `Connect`
2.2.0 / 2011-03-30
2.2.0 / 2011-03-30
==================
* Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606
@@ -262,14 +519,14 @@ Shaw]
* Added `app.VERB(path)` as alias of `app.lookup.VERB()`.
* Dependency `connect >= 1.2.0`
2.1.1 / 2011-03-29
2.1.1 / 2011-03-29
==================
* Added; expose `err.view` object when failing to locate a view
* Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann]
* Fixed; `res.send(undefined)` responds with 204 [aheckmann]
2.1.0 / 2011-03-24
2.1.0 / 2011-03-24
==================
* Added `<root>/_?<name>` partial lookup support. Closes #447
@@ -280,20 +537,20 @@ Shaw]
* Fixed stylus example for latest version
* Fixed; wrap try/catch around `res.render()`
2.0.0 / 2011-03-17
2.0.0 / 2011-03-17
==================
* Fixed up index view path alternative.
* Changed; `res.locals()` without object returns the locals
2.0.0rc3 / 2011-03-17
2.0.0rc3 / 2011-03-17
==================
* Added `res.locals(obj)` to compliment `res.local(key, val)`
* Added `res.partial()` callback support
* Fixed recursive error reporting issue in `res.render()`
2.0.0rc2 / 2011-03-17
2.0.0rc2 / 2011-03-17
==================
* Changed; `partial()` "locals" are now optional
@@ -302,14 +559,14 @@ Shaw]
* Fixed blog example
* Fixed `{req,res}.app` reference when mounting [Ben Weaver]
2.0.0rc / 2011-03-14
2.0.0rc / 2011-03-14
==================
* Fixed; expose `HTTPSServer` constructor
* Fixed express(1) default test charset. Closes #579 [reported by secoif]
* Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP]
2.0.0beta3 / 2011-03-09
2.0.0beta3 / 2011-03-09
==================
* Added support for `res.contentType()` literal
@@ -327,13 +584,13 @@ Shaw]
* Fixed; default `res.send()` string charset to utf8
* Removed `Partial` constructor (not currently used)
2.0.0beta2 / 2011-03-07
2.0.0beta2 / 2011-03-07
==================
* Added res.render() `.locals` support back to aid in migration process
* Fixed flash example
2.0.0beta / 2011-03-03
2.0.0beta / 2011-03-03
==================
* Added HTTPS support
@@ -366,46 +623,46 @@ Shaw]
* Fixed; strip unsafe chars from jsonp callbacks
* Removed "stream threshold" setting
1.0.8 / 2011-03-01
1.0.8 / 2011-03-01
==================
* Allow `req.query` to be pre-defined (via middleware or other parent app)
* "connect": ">= 0.5.0 < 1.0.0". Closes #547
* Removed the long deprecated __EXPRESS_ENV__ support
1.0.7 / 2011-02-07
1.0.7 / 2011-02-07
==================
* Fixed `render()` setting inheritance.
Mounted apps would not inherit "view engine"
1.0.6 / 2011-02-07
1.0.6 / 2011-02-07
==================
* Fixed `view engine` setting bug when period is in dirname
1.0.5 / 2011-02-05
1.0.5 / 2011-02-05
==================
* Added secret to generated app `session()` call
1.0.4 / 2011-02-05
1.0.4 / 2011-02-05
==================
* Added `qs` dependency to _package.json_
* Fixed namespaced `require()`s for latest connect support
1.0.3 / 2011-01-13
1.0.3 / 2011-01-13
==================
* Remove unsafe characters from JSONP callback names [Ryan Grove]
1.0.2 / 2011-01-10
1.0.2 / 2011-01-10
==================
* Removed nested require, using `connect.router`
1.0.1 / 2010-12-29
1.0.1 / 2010-12-29
==================
* Fixed for middleware stacked via `createServer()`
@@ -413,7 +670,7 @@ Shaw]
would not have access to Express methods such as `res.send()`
or props like `req.query` etc.
1.0.0 / 2010-11-16
1.0.0 / 2010-11-16
==================
* Added; deduce partial object names from the last segment.
@@ -427,7 +684,7 @@ Shaw]
* Added _-s, --session[s]_ flag to express(1) to add session related middleware
* Added _--template_ flag to express(1) to specify the
template engine to use.
* Added _--css_ flag to express(1) to specify the
* Added _--css_ flag to express(1) to specify the
stylesheet engine to use (or just plain css by default).
* Added `app.all()` support [thanks aheckmann]
* Added partial direct object support.
@@ -440,7 +697,7 @@ Shaw]
* Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454
* Fixed jsonp support; _text/javascript_ as per mailinglist discussion
1.0.0rc4 / 2010-10-14
1.0.0rc4 / 2010-10-14
==================
* Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0
@@ -459,7 +716,7 @@ Shaw]
* Fixed; exposing _./support_ libs to examples so they can run without installs
* Fixed mvc example
1.0.0rc3 / 2010-09-20
1.0.0rc3 / 2010-09-20
==================
* Added confirmation for `express(1)` app generation. Closes #391
@@ -482,7 +739,7 @@ Shaw]
* Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo]
1.0.0rc2 / 2010-08-17
1.0.0rc2 / 2010-08-17
==================
* Added `app.register()` for template engine mapping. Closes #390
@@ -495,7 +752,7 @@ Shaw]
* Fixed `res.sendfile()` error handling, defer via `next()`
* Fixed `res.render()` callback when a layout is used [thanks guillermo]
* Fixed; `make install` creating ~/.node_libraries when not present
* Fixed issue preventing error handlers from being defined anywhere. Closes #387
* Fixed issue preventing error handlers from being defined anywhere. Closes #387
1.0.0rc / 2010-07-28
==================
@@ -513,7 +770,7 @@ Shaw]
* Fixed "home" setting
* Fixed middleware/router precedence issue. Closes #366
* Fixed; _configure()_ callbacks called immediately. Closes #368
1.0.0beta2 / 2010-07-23
==================
@@ -648,7 +905,7 @@ Shaw]
* Updated dependencies
* Removed set("session cookie") in favour of use(Session, { cookie: { ... }})
* Removed utils.mixin(); use Object#mergeDeep()
0.8.0 / 2010-03-19
==================
@@ -715,16 +972,16 @@ Shaw]
* Added seed.yml for kiwi package management support
* Added HTTP client query string support when method is GET. Closes #205
* Added support for arbitrary view engines.
For example "foo.engine.html" will now require('engine'),
the exports from this module are cached after the first require().
* Added async plugin support
* Removed usage of RESTful route funcs as http client
get() etc, use http.get() and friends
* Removed custom exceptions
0.5.0 / 2010-03-10

48
test/node_modules/express/Makefile generated vendored
View File

@@ -1,29 +1,33 @@
DOCS = $(shell find docs/*.md)
HTMLDOCS = $(DOCS:.md=.html)
TESTS = $(shell find test/*.test.js)
MOCHA_OPTS=
REPORTER = dot
test:
@NODE_ENV=test ./node_modules/.bin/expresso $(TESTS)
check: test
docs: $(HTMLDOCS)
@ echo "... generating TOC"
@./support/toc.js docs/guide.html
test: test-unit test-acceptance
%.html: %.md
@echo "... $< -> $@"
@markdown $< \
| cat docs/layout/head.html - docs/layout/foot.html \
> $@
test-unit:
@NODE_ENV=test ./node_modules/.bin/mocha \
--reporter $(REPORTER) \
$(MOCHA_OPTS)
site:
rm -fr /tmp/docs \
&& cp -fr docs /tmp/docs \
&& git checkout gh-pages \
&& cp -fr /tmp/docs/* . \
&& echo "done"
test-acceptance:
@NODE_ENV=test ./node_modules/.bin/mocha \
--reporter $(REPORTER) \
--bail \
test/acceptance/*.js
docclean:
rm -f docs/*.{1,html}
test-cov: lib-cov
@EXPRESS_COV=1 $(MAKE) test REPORTER=html-cov > coverage.html
.PHONY: site test docs docclean
lib-cov:
@jscoverage lib lib-cov
benchmark:
@./support/bench
clean:
rm -f coverage.html
rm -fr lib-cov
.PHONY: test test-unit test-acceptance benchmark clean

168
test/node_modules/express/Readme.md generated vendored
View File

@@ -1,23 +1,20 @@
![express logo](http://f.cl.ly/items/0V2S1n0K1i3y1c122g04/Screen%20Shot%202012-04-11%20at%209.59.42%20AM.png)
# Express
Insanely fast (and small) server-side JavaScript web development framework
built on [node](http://nodejs.org) and [Connect](http://github.com/senchalabs/connect).
var app = express.createServer();
app.get('/', function(req, res){
res.send('Hello World');
});
app.listen(3000);
Fast, unopinionated, minimalist web framework for [node](http://nodejs.org). [![Build Status](https://secure.travis-ci.org/visionmedia/express.png)](http://travis-ci.org/visionmedia/express)
```js
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('Hello World');
});
app.listen(3000);
```
## Installation
$ npm install express
or to access the `express(1)` executable install globally:
$ npm install -g express
## Quick Start
@@ -31,83 +28,56 @@ or to access the `express(1)` executable install globally:
Install dependencies:
$ npm install -d
$ npm install
Start the server:
$ node app.js
$ node app
## Features
* Built on [Connect](http://github.com/senchalabs/connect)
* Robust routing
* Redirection helpers
* Dynamic view helpers
* HTTP helpers (redirection, caching, etc)
* View system supporting 14+ template engines
* Content negotiation
* Focus on high performance
* View rendering and partials support
* Environment based configuration
* Session based flash notifications
* Built on [Connect](http://github.com/senchalabs/connect)
* High test coverage
* Executable for generating applications quickly
* Application level view options
* High test coverage
Via Connect:
## Philosophy
* Session support
* Cache API
* Mime helpers
* ETag support
* Persistent flash notifications
* Cookie support
* JSON-RPC
* Logging
* and _much_ more!
## Contributors
The following are the major contributors of Express (in no specific order).
* TJ Holowaychuk ([visionmedia](http://github.com/visionmedia))
* Ciaran Jessup ([ciaranj](http://github.com/ciaranj))
* Aaron Heckmann ([aheckmann](http://github.com/aheckmann))
* Guillermo Rauch ([guille](http://github.com/guille))
The Express philosophy is to provide small, robust tooling for HTTP servers. Making
it a great solution for single page applications, web sites, hybrids, or public
HTTP APIs.
Built on Connect you can use _only_ what you need, and nothing more, applications
can be as big or as small as you like, even a single file. Express does
not force you to use any specific ORM or template engine. With support for over
14 template engines via [Consolidate.js](http://github.com/visionmedia/consolidate.js)
you can quickly craft your perfect framework.
## More Information
* #express on freenode
* [express-expose](http://github.com/visionmedia/express-expose) expose objects, functions, modules and more to client-side js with ease
* [express-configure](http://github.com/visionmedia/express-configuration) async configuration support
* [express-messages](http://github.com/visionmedia/express-messages) flash notification rendering helper
* [express-namespace](http://github.com/visionmedia/express-namespace) namespaced route support
* [express-params](https://github.com/visionmedia/express-params) param pre-condition functions
* [express-mongoose](https://github.com/LearnBoost/express-mongoose) plugin for easy rendering of Mongoose async Query results
* Follow [tjholowaychuk](http://twitter.com/tjholowaychuk) on twitter for updates
* Join #express on freenode
* [Google Group](http://groups.google.com/group/express-js) for discussion
* Follow [tjholowaychuk](http://twitter.com/tjholowaychuk) on twitter for updates
* Visit the [Wiki](http://github.com/visionmedia/express/wiki)
* [日本語ドキュメンテーション](http://hideyukisaito.com/doc/expressjs/) by [hideyukisaito](https://github.com/hideyukisaito)
* Screencast - [Introduction](http://bit.ly/eRYu0O)
* Screencast - [View Partials](http://bit.ly/dU13Fx)
* Screencast - [Route Specific Middleware](http://bit.ly/hX4IaH)
* Screencast - [Route Path Placeholder Preconditions](http://bit.ly/eNqmVs)
## Node Compatibility
Express 1.x is compatible with node 0.2.x and connect < 1.0.
Express 2.x is compatible with node 0.4.x or 0.6.x, and connect 1.x
Express 3.x (master) will be compatible with node 0.6.x and connect 2.x
* [Русскоязычная документация](http://express-js.ru/)
## Viewing Examples
First install the dev dependencies to install all the example / test suite deps:
Clone the Express repo, then install the dev dependencies to install all the example / test suite deps:
$ git clone git://github.com/visionmedia/express.git --depth 1
$ cd express
$ npm install
then run whichever tests you want:
$ node examples/jade/app.js
$ node examples/content-negotiation
## Running Tests
@@ -119,11 +89,75 @@ then run the tests:
$ make test
## Contributors
```
project: express
commits: 3559
active : 468 days
files : 237
authors:
1891 Tj Holowaychuk 53.1%
1285 visionmedia 36.1%
182 TJ Holowaychuk 5.1%
54 Aaron Heckmann 1.5%
34 csausdev 1.0%
26 ciaranj 0.7%
21 Robert Sköld 0.6%
6 Guillermo Rauch 0.2%
3 Dav Glass 0.1%
3 Nick Poulden 0.1%
2 Randy Merrill 0.1%
2 Benny Wong 0.1%
2 Hunter Loftis 0.1%
2 Jake Gordon 0.1%
2 Brian McKinney 0.1%
2 Roman Shtylman 0.1%
2 Ben Weaver 0.1%
2 Dave Hoover 0.1%
2 Eivind Fjeldstad 0.1%
2 Daniel Shaw 0.1%
1 Matt Colyer 0.0%
1 Pau Ramon 0.0%
1 Pero Pejovic 0.0%
1 Peter Rekdal Sunde 0.0%
1 Raynos 0.0%
1 Teng Siong Ong 0.0%
1 Viktor Kelemen 0.0%
1 ctide 0.0%
1 8bitDesigner 0.0%
1 isaacs 0.0%
1 mgutz 0.0%
1 pikeas 0.0%
1 shuwatto 0.0%
1 tstrimple 0.0%
1 ewoudj 0.0%
1 Adam Sanderson 0.0%
1 Andrii Kostenko 0.0%
1 Andy Hiew 0.0%
1 Arpad Borsos 0.0%
1 Ashwin Purohit 0.0%
1 Benjen 0.0%
1 Darren Torpey 0.0%
1 Greg Ritter 0.0%
1 Gregory Ritter 0.0%
1 James Herdman 0.0%
1 Jim Snodgrass 0.0%
1 Joe McCann 0.0%
1 Jonathan Dumaine 0.0%
1 Jonathan Palardy 0.0%
1 Jonathan Zacsh 0.0%
1 Justin Lilly 0.0%
1 Ken Sato 0.0%
1 Maciej Małecki 0.0%
1 Masahiro Hayashi 0.0%
```
## License
(The MIT License)
Copyright (c) 2009-2011 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
Copyright (c) 2009-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

369
test/node_modules/express/bin/express generated vendored Normal file → Executable file
View File

@@ -4,64 +4,40 @@
* Module dependencies.
*/
var fs = require('fs')
var exec = require('child_process').exec
, program = require('commander')
, mkdirp = require('mkdirp')
, pkg = require('../package.json')
, version = pkg.version
, os = require('os')
, exec = require('child_process').exec
, mkdirp = require('mkdirp');
, fs = require('fs');
/**
* Package information.
*/
// CLI
var pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json'));
program
.version(version)
.option('-s, --sessions', 'add session support')
.option('-e, --ejs', 'add ejs engine support (defaults to jade)')
.option('-J, --jshtml', 'add jshtml engine support (defaults to jade)')
.option('-H, --hogan', 'add hogan.js engine support')
.option('-c, --css <engine>', 'add stylesheet <engine> support (less|stylus) (defaults to plain css)')
.option('-f, --force', 'force on non-empty directory')
.parse(process.argv);
/**
* Framework version.
*/
// Path
var version = pkg.version;
var path = program.args.shift() || '.';
/**
* Add session support.
*/
// end-of-line code
var sessions = false;
var eol = 'win32' == os.platform() ? '\r\n' : '\n'
/**
* CSS engine to utilize.
*/
// Template engine
var cssEngine;
/**
* End-of-line code.
*/
var eol = os.platform
? ('win32' == os.platform() ? '\r\n' : '\n')
: '\n';
/**
* Template engine to utilize.
*/
var templateEngine = 'jade';
/**
* Usage documentation.
*/
var usage = ''
+ '\n'
+ ' Usage: express [options] [path]\n'
+ '\n'
+ ' Options:\n'
+ ' -s, --sessions add session support\n'
+ ' -t, --template <engine> add template <engine> support (jade|ejs). default=jade\n'
+ ' -c, --css <engine> add stylesheet <engine> support (stylus). default=plain css\n'
+ ' -v, --version output framework version\n'
+ ' -h, --help output help information\n'
;
program.template = 'jade';
if (program.ejs) program.template = 'ejs';
if (program.jshtml) program.template = 'jshtml';
if (program.hogan) program.template = 'hjs';
/**
* Routes index template.
@@ -74,7 +50,22 @@ var index = [
, ' */'
, ''
, 'exports.index = function(req, res){'
, ' res.render(\'index\', { title: \'Express\' })'
, ' res.render(\'index\', { title: \'Express\' });'
, '};'
].join(eol);
/**
* Routes users template.
*/
var users = [
''
, '/*'
, ' * GET users listing.'
, ' */'
, ''
, 'exports.list = function(req, res){'
, ' res.send("respond with a resource");'
, '};'
].join(eol);
@@ -83,12 +74,13 @@ var index = [
*/
var jadeLayout = [
'!!!'
'doctype 5'
, 'html'
, ' head'
, ' title= title'
, ' link(rel=\'stylesheet\', href=\'/stylesheets/style.css\')'
, ' body!= body'
, ' body'
, ' block content'
].join(eol);
/**
@@ -96,25 +88,11 @@ var jadeLayout = [
*/
var jadeIndex = [
'h1= title'
, 'p Welcome to #{title}'
].join(eol);
/**
* EJS layout template.
*/
var ejsLayout = [
'<!DOCTYPE html>'
, '<html>'
, ' <head>'
, ' <title><%= title %></title>'
, ' <link rel=\'stylesheet\' href=\'/stylesheets/style.css\' />'
, ' </head>'
, ' <body>'
, ' <%- body %>'
, ' </body>'
, '</html>'
'extends layout'
, ''
, 'block content'
, ' h1= title'
, ' p Welcome to #{title}'
].join(eol);
/**
@@ -122,9 +100,61 @@ var ejsLayout = [
*/
var ejsIndex = [
'<h1><%= title %></h1>'
, '<p>Welcome to <%= title %></p>'
].join(eol);
'<!DOCTYPE html>'
, '<html>'
, ' <head>'
, ' <title><%= title %></title>'
, ' <link rel=\'stylesheet\' href=\'/stylesheets/style.css\' />'
, ' </head>'
, ' <body>'
, ' <h1><%= title %></h1>'
, ' <p>Welcome to <%= title %></p>'
, ' </body>'
, '</html>'
].join(eol);
/**
* JSHTML layout template.
*/
var jshtmlLayout = [
'<!DOCTYPE html>'
, '<html>'
, ' <head>'
, ' <title> @write(title) </title>'
, ' <link rel=\'stylesheet\' href=\'/stylesheets/style.css\' />'
, ' </head>'
, ' <body>'
, ' @write(body)'
, ' </body>'
, '</html>'
].join(eol);
/**
* JSHTML index template.
*/
var jshtmlIndex = [
'<h1>@write(title)</h1>'
, '<p>Welcome to @write(title)</p>'
].join(eol);
/**
* Hogan.js index template.
*/
var hoganIndex = [
'<!DOCTYPE html>'
, '<html>'
, ' <head>'
, ' <title>{{ title }}</title>'
, ' <link rel=\'stylesheet\' href=\'/stylesheets/style.css\' />'
, ' </head>'
, ' <body>'
, ' <h1>{{ title }}</h1>'
, ' <p>Welcome to {{ title }}</p>'
, ' </body>'
, '</html>'
].join(eol);
/**
* Default css template.
@@ -141,6 +171,21 @@ var css = [
, '}'
].join(eol);
/**
* Default less template.
*/
var less = [
'body {'
, ' padding: 50px;'
, ' font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;'
, '}'
, ''
, 'a {'
, ' color: #00B7FF;'
, '}'
].join(eol);
/**
* Default stylus template.
*/
@@ -164,85 +209,46 @@ var app = [
, ' */'
, ''
, 'var express = require(\'express\')'
, ' , routes = require(\'./routes\');'
, ' , routes = require(\'./routes\')'
, ' , user = require(\'./routes/user\')'
, ' , http = require(\'http\')'
, ' , path = require(\'path\');'
, ''
, 'var app = module.exports = express.createServer();'
, ''
, '// Configuration'
, 'var app = express();'
, ''
, 'app.configure(function(){'
, ' app.set(\'port\', process.env.PORT || 3000);'
, ' app.set(\'views\', __dirname + \'/views\');'
, ' app.set(\'view engine\', \':TEMPLATE\');'
, ' app.use(express.favicon());'
, ' app.use(express.logger(\'dev\'));'
, ' app.use(express.bodyParser());'
, ' app.use(express.methodOverride());{sess}{css}'
, ' app.use(app.router);'
, ' app.use(express.static(__dirname + \'/public\'));'
, ' app.use(express.methodOverride());{sess}'
, ' app.use(app.router);{css}'
, ' app.use(express.static(path.join(__dirname, \'public\')));'
, '});'
, ''
, 'app.configure(\'development\', function(){'
, ' app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));'
, '});'
, ''
, 'app.configure(\'production\', function(){'
, ' app.use(express.errorHandler());'
, '});'
, ''
, '// Routes'
, ''
, 'app.get(\'/\', routes.index);'
, 'app.get(\'/users\', user.list);'
, ''
, 'app.listen(3000, function(){'
, ' console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);'
, 'http.createServer(app).listen(app.get(\'port\'), function(){'
, ' console.log("Express server listening on port " + app.get(\'port\'));'
, '});'
, ''
].join(eol);
// Parse arguments
var args = process.argv.slice(2)
, path = '.';
while (args.length) {
var arg = args.shift();
switch (arg) {
case '-h':
case '--help':
abort(usage);
break;
case '-v':
case '--version':
abort(version);
break;
case '-s':
case '--session':
case '--sessions':
sessions = true;
break;
case '-c':
case '--css':
args.length
? (cssEngine = args.shift())
: abort('--css requires an argument');
break;
case '-t':
case '--template':
args.length
? (templateEngine = args.shift())
: abort('--template requires an argument');
break;
default:
path = arg;
}
}
// Generate application
(function createApplication(path) {
emptyDirectory(path, function(empty){
if (empty) {
if (empty || program.force) {
createApplicationAt(path);
} else {
confirm('destination is not empty, continue? ', function(ok){
program.confirm('destination is not empty, continue? ', function(ok){
if (ok) {
process.stdin.destroy();
createApplicationAt(path);
@@ -264,8 +270,11 @@ function createApplicationAt(path) {
console.log();
process.on('exit', function(){
console.log();
console.log(' dont forget to install dependencies:');
console.log(' $ cd %s && npm install', path);
console.log(' install dependencies:');
console.log(' $ cd %s && npm install', path);
console.log();
console.log(' run the app:');
console.log(' $ node app');
console.log();
});
@@ -274,7 +283,10 @@ function createApplicationAt(path) {
mkdir(path + '/public/javascripts');
mkdir(path + '/public/images');
mkdir(path + '/public/stylesheets', function(){
switch (cssEngine) {
switch (program.css) {
case 'less':
write(path + '/public/stylesheets/style.less', less);
break;
case 'stylus':
write(path + '/public/stylesheets/style.styl', stylus);
break;
@@ -285,52 +297,74 @@ function createApplicationAt(path) {
mkdir(path + '/routes', function(){
write(path + '/routes/index.js', index);
write(path + '/routes/user.js', users);
});
mkdir(path + '/views', function(){
switch (templateEngine) {
switch (program.template) {
case 'ejs':
write(path + '/views/layout.ejs', ejsLayout);
write(path + '/views/index.ejs', ejsIndex);
break;
case 'jade':
write(path + '/views/layout.jade', jadeLayout);
write(path + '/views/index.jade', jadeIndex);
break;
case 'jshtml':
write(path + '/views/layout.jshtml', jshtmlLayout);
write(path + '/views/index.jshtml', jshtmlIndex);
break;
case 'hjs':
write(path + '/views/index.hjs', hoganIndex);
break;
}
});
// CSS Engine support
switch (cssEngine) {
switch (program.css) {
case 'less':
app = app.replace('{css}', eol + ' app.use(require(\'less-middleware\')({ src: __dirname + \'/public\' }));');
break;
case 'stylus':
app = app.replace('{css}', eol + ' app.use(require(\'stylus\').middleware({ src: __dirname + \'/public\' }));');
app = app.replace('{css}', eol + ' app.use(require(\'stylus\').middleware(__dirname + \'/public\'));');
break;
default:
app = app.replace('{css}', '');
}
// Session support
app = app.replace('{sess}', sessions
? eol + ' app.use(express.cookieParser());' + eol + ' app.use(express.session({ secret: \'your secret here\' }));'
app = app.replace('{sess}', program.sessions
? eol + ' app.use(express.cookieParser(\'your secret here\'));' + eol + ' app.use(express.session());'
: '');
// Template support
app = app.replace(':TEMPLATE', templateEngine);
app = app.replace(':TEMPLATE', program.template);
// package.json
var json = '{' + eol;
json += ' "name": "application-name"' + eol;
json += ' , "version": "0.0.1"' + eol;
json += ' , "private": true' + eol;
json += ' , "dependencies": {' + eol;
json += ' "express": "' + version + '"' + eol;
if (cssEngine) json += ' , "' + cssEngine + '": ">= 0.0.1"' + eol;
if (templateEngine) json += ' , "' + templateEngine + '": ">= 0.0.1"' + eol;
json += ' }' + eol;
json += '}';
var pkg = {
name: 'application-name'
, version: '0.0.1'
, private: true
, scripts: { start: 'node app' }
, dependencies: {
express: version
}
}
if (program.template) pkg.dependencies[program.template] = '*';
write(path + '/package.json', json);
// CSS Engine support
switch (program.css) {
case 'less':
pkg.dependencies['less-middleware'] = '*';
break;
default:
if (program.css) {
pkg.dependencies[program.css] = '*';
}
}
write(path + '/package.json', JSON.stringify(pkg, null, 2));
write(path + '/app.js', app);
});
}
@@ -361,41 +395,6 @@ function write(path, str) {
console.log(' \x1b[36mcreate\x1b[0m : ' + path);
}
/**
* Prompt confirmation with the given `msg`.
*
* @param {String} msg
* @param {Function} fn
*/
function confirm(msg, fn) {
prompt(msg, function(val){
fn(/^ *y(es)?/i.test(val));
});
}
/**
* Prompt input with the given `msg` and callback `fn`.
*
* @param {String} msg
* @param {Function} fn
*/
function prompt(msg, fn) {
// prompt
if (' ' == msg[msg.length - 1]) {
process.stdout.write(msg);
} else {
console.log(msg);
}
// stdin
process.stdin.setEncoding('ascii');
process.stdin.once('data', function(data){
fn(data);
}).resume();
}
/**
* Mkdir -p.
*

25
test/node_modules/express/client.js generated vendored Normal file
View File

@@ -0,0 +1,25 @@
var http = require('http');
var times = 50;
while (times--) {
var req = http.request({
port: 3000
, method: 'POST'
, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
req.on('response', function(res){
console.log(res.statusCode);
});
var n = 500000;
while (n--) {
req.write('foo=bar&bar=baz&');
}
req.write('foo=bar&bar=baz');
req.end();
}

4
test/node_modules/express/index.js generated vendored
View File

@@ -1,2 +1,4 @@
module.exports = require('./lib/express');
module.exports = process.env.EXPRESS_COV
? require('./lib-cov/express')
: require('./lib/express');

533
test/node_modules/express/lib/application.js generated vendored Normal file
View File

@@ -0,0 +1,533 @@
/**
* Module dependencies.
*/
var connect = require('connect')
, Router = require('./router')
, methods = require('methods')
, middleware = require('./middleware')
, debug = require('debug')('express:application')
, locals = require('./utils').locals
, View = require('./view')
, utils = connect.utils
, path = require('path')
, http = require('http')
, join = path.join;
/**
* Application prototype.
*/
var app = exports = module.exports = {};
/**
* Initialize the server.
*
* - setup default configuration
* - setup default middleware
* - setup route reflection methods
*
* @api private
*/
app.init = function(){
this.cache = {};
this.settings = {};
this.engines = {};
this.viewCallbacks = [];
this.defaultConfiguration();
};
/**
* Initialize application configuration.
*
* @api private
*/
app.defaultConfiguration = function(){
// default settings
this.enable('x-powered-by');
this.set('env', process.env.NODE_ENV || 'development');
debug('booting in %s mode', this.get('env'));
// implicit middleware
this.use(connect.query());
this.use(middleware.init(this));
// inherit protos
this.on('mount', function(parent){
this.request.__proto__ = parent.request;
this.response.__proto__ = parent.response;
this.engines.__proto__ = parent.engines;
});
// router
this._router = new Router(this);
this.routes = this._router.map;
this.__defineGetter__('router', function(){
this._usedRouter = true;
this._router.caseSensitive = this.enabled('case sensitive routing');
this._router.strict = this.enabled('strict routing');
return this._router.middleware;
});
// setup locals
this.locals = locals(this);
// default locals
this.locals.settings = this.settings;
// default configuration
this.set('views', process.cwd() + '/views');
this.set('jsonp callback name', 'callback');
this.configure('development', function(){
this.set('json spaces', 2);
});
this.configure('production', function(){
this.enable('view cache');
});
};
/**
* Proxy `connect#use()` to apply settings to
* mounted applications.
*
* @param {String|Function|Server} route
* @param {Function|Server} fn
* @return {app} for chaining
* @api public
*/
app.use = function(route, fn){
var app;
// default route to '/'
if ('string' != typeof route) fn = route, route = '/';
// express app
if (fn.handle && fn.set) app = fn;
// restore .app property on req and res
if (app) {
app.route = route;
fn = function(req, res, next) {
var orig = req.app;
app.handle(req, res, function(err){
req.app = res.app = orig;
req.__proto__ = orig.request;
res.__proto__ = orig.response;
next(err);
});
};
}
connect.proto.use.call(this, route, fn);
// mounted an app
if (app) {
app.parent = this;
app.emit('mount', this);
}
return this;
};
/**
* Register the given template engine callback `fn`
* as `ext`.
*
* By default will `require()` the engine based on the
* file extension. For example if you try to render
* a "foo.jade" file Express will invoke the following internally:
*
* app.engine('jade', require('jade').__express);
*
* For engines that do not provide `.__express` out of the box,
* or if you wish to "map" a different extension to the template engine
* you may use this method. For example mapping the EJS template engine to
* ".html" files:
*
* app.engine('html', require('ejs').renderFile);
*
* In this case EJS provides a `.renderFile()` method with
* the same signature that Express expects: `(path, options, callback)`,
* though note that it aliases this method as `ejs.__express` internally
* so if you're using ".ejs" extensions you dont need to do anything.
*
* Some template engines do not follow this convention, the
* [Consolidate.js](https://github.com/visionmedia/consolidate.js)
* library was created to map all of node's popular template
* engines to follow this convention, thus allowing them to
* work seemlessly within Express.
*
* @param {String} ext
* @param {Function} fn
* @return {app} for chaining
* @api public
*/
app.engine = function(ext, fn){
if ('function' != typeof fn) throw new Error('callback function required');
if ('.' != ext[0]) ext = '.' + ext;
this.engines[ext] = fn;
return this;
};
/**
* Map the given param placeholder `name`(s) to the given callback(s).
*
* Parameter mapping is used to provide pre-conditions to routes
* which use normalized placeholders. For example a _:user_id_ parameter
* could automatically load a user's information from the database without
* any additional code,
*
* The callback uses the samesignature as middleware, the only differencing
* being that the value of the placeholder is passed, in this case the _id_
* of the user. Once the `next()` function is invoked, just like middleware
* it will continue on to execute the route, or subsequent parameter functions.
*
* app.param('user_id', function(req, res, next, id){
* User.find(id, function(err, user){
* if (err) {
* next(err);
* } else if (user) {
* req.user = user;
* next();
* } else {
* next(new Error('failed to load user'));
* }
* });
* });
*
* @param {String|Array} name
* @param {Function} fn
* @return {app} for chaining
* @api public
*/
app.param = function(name, fn){
var self = this
, fns = [].slice.call(arguments, 1);
// array
if (Array.isArray(name)) {
name.forEach(function(name){
fns.forEach(function(fn){
self.param(name, fn);
});
});
// param logic
} else if ('function' == typeof name) {
this._router.param(name);
// single
} else {
if (':' == name[0]) name = name.substr(1);
fns.forEach(function(fn){
self._router.param(name, fn);
});
}
return this;
};
/**
* Assign `setting` to `val`, or return `setting`'s value.
*
* app.set('foo', 'bar');
* app.get('foo');
* // => "bar"
*
* Mounted servers inherit their parent server's settings.
*
* @param {String} setting
* @param {String} val
* @return {Server} for chaining
* @api public
*/
app.set = function(setting, val){
if (1 == arguments.length) {
if (this.settings.hasOwnProperty(setting)) {
return this.settings[setting];
} else if (this.parent) {
return this.parent.set(setting);
}
} else {
this.settings[setting] = val;
return this;
}
};
/**
* Return the app's absolute pathname
* based on the parent(s) that have
* mounted it.
*
* For example if the application was
* mounted as "/admin", which itself
* was mounted as "/blog" then the
* return value would be "/blog/admin".
*
* @return {String}
* @api private
*/
app.path = function(){
return this.parent
? this.parent.path() + this.route
: '';
};
/**
* Check if `setting` is enabled (truthy).
*
* app.enabled('foo')
* // => false
*
* app.enable('foo')
* app.enabled('foo')
* // => true
*
* @param {String} setting
* @return {Boolean}
* @api public
*/
app.enabled = function(setting){
return !!this.set(setting);
};
/**
* Check if `setting` is disabled.
*
* app.disabled('foo')
* // => true
*
* app.enable('foo')
* app.disabled('foo')
* // => false
*
* @param {String} setting
* @return {Boolean}
* @api public
*/
app.disabled = function(setting){
return !this.set(setting);
};
/**
* Enable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @api public
*/
app.enable = function(setting){
return this.set(setting, true);
};
/**
* Disable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @api public
*/
app.disable = function(setting){
return this.set(setting, false);
};
/**
* Configure callback for zero or more envs,
* when no `env` is specified that callback will
* be invoked for all environments. Any combination
* can be used multiple times, in any order desired.
*
* Examples:
*
* app.configure(function(){
* // executed for all envs
* });
*
* app.configure('stage', function(){
* // executed staging env
* });
*
* app.configure('stage', 'production', function(){
* // executed for stage and production
* });
*
* Note:
*
* These callbacks are invoked immediately, and
* are effectively sugar for the following:
*
* var env = process.env.NODE_ENV || 'development';
*
* switch (env) {
* case 'development':
* ...
* break;
* case 'stage':
* ...
* break;
* case 'production':
* ...
* break;
* }
*
* @param {String} env...
* @param {Function} fn
* @return {app} for chaining
* @api public
*/
app.configure = function(env, fn){
var envs = 'all'
, args = [].slice.call(arguments);
fn = args.pop();
if (args.length) envs = args;
if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);
return this;
};
/**
* Delegate `.VERB(...)` calls to `router.VERB(...)`.
*/
methods.forEach(function(method){
app[method] = function(path){
if ('get' == method && 1 == arguments.length) return this.set(path);
// if no router attacked yet, attach the router
if (!this._usedRouter) this.use(this.router);
// setup route
this._router[method].apply(this._router, arguments);
return this;
};
});
/**
* Special-cased "all" method, applying the given route `path`,
* middleware, and callback to _every_ HTTP method.
*
* @param {String} path
* @param {Function} ...
* @return {app} for chaining
* @api public
*/
app.all = function(path){
var args = arguments;
methods.forEach(function(method){
app[method].apply(this, args);
}, this);
return this;
};
// del -> delete alias
app.del = app.delete;
/**
* Render the given view `name` name with `options`
* and a callback accepting an error and the
* rendered template string.
*
* Example:
*
* app.render('email', { name: 'Tobi' }, function(err, html){
* // ...
* })
*
* @param {String} name
* @param {String|Function} options or fn
* @param {Function} fn
* @api public
*/
app.render = function(name, options, fn){
var opts = {}
, cache = this.cache
, engines = this.engines
, view;
// support callback function as second arg
if ('function' == typeof options) {
fn = options, options = {};
}
// merge app.locals
utils.merge(opts, this.locals);
// merge options._locals
if (options._locals) utils.merge(opts, options._locals);
// merge options
utils.merge(opts, options);
// set .cache unless explicitly provided
opts.cache = null == opts.cache
? this.enabled('view cache')
: opts.cache;
// primed cache
if (opts.cache) view = cache[name];
// view
if (!view) {
view = new View(name, {
defaultEngine: this.get('view engine'),
root: this.get('views'),
engines: engines
});
if (!view.path) {
var err = new Error('Failed to lookup view "' + name + '"');
err.view = view;
return fn(err);
}
// prime the cache
if (opts.cache) cache[name] = view;
}
// render
try {
view.render(opts, fn);
} catch (err) {
fn(err);
}
};
/**
* Listen for connections.
*
* A node `http.Server` is returned, with this
* application (which is a `Function`) as its
* callback. If you wish to create both an HTTP
* and HTTPS server you may do so with the "http"
* and "https" modules as shown here:
*
* var http = require('http')
* , https = require('https')
* , express = require('express')
* , app = express();
*
* http.createServer(app).listen(80);
* https.createServer({ ... }, app).listen(443);
*
* @return {http.Server}
* @api public
*/
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};

View File

@@ -1,77 +1,90 @@
/*!
* Express
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var connect = require('connect')
, HTTPSServer = require('./https')
, HTTPServer = require('./http')
, proto = require('./application')
, Route = require('./router/route')
, Router = require('./router')
, req = require('./request')
, res = require('./response')
, utils = connect.utils;
/**
* Re-export connect auto-loaders.
*
* This prevents the need to `require('connect')` in order
* to access core middleware, so for example `express.logger()` instead
* of `require('connect').logger()`.
* Expose `createApplication()`.
*/
var exports = module.exports = connect.middleware;
exports = module.exports = createApplication;
/**
* Framework version.
*/
exports.version = '2.5.11';
exports.version = '3.0.5';
/**
* Shortcut for `new Server(...)`.
* Expose mime.
*/
exports.mime = connect.mime;
/**
* Create an express application.
*
* @param {Function} ...
* @return {Server}
* @return {Function}
* @api public
*/
exports.createServer = function(options){
if ('object' == typeof options) {
return new HTTPSServer(options, Array.prototype.slice.call(arguments, 1));
} else {
return new HTTPServer(Array.prototype.slice.call(arguments));
}
function createApplication() {
var app = connect();
utils.merge(app, proto);
app.request = { __proto__: req };
app.response = { __proto__: res };
app.init();
return app;
}
/**
* Expose connect.middleware as express.*
* for example `express.logger` etc.
*/
for (var key in connect.middleware) {
Object.defineProperty(
exports
, key
, Object.getOwnPropertyDescriptor(connect.middleware, key));
}
/**
* Error on createServer().
*/
exports.createServer = function(){
console.warn('Warning: express.createServer() is deprecated, express');
console.warn('applications no longer inherit from http.Server,');
console.warn('please use:');
console.warn('');
console.warn(' var express = require("express");');
console.warn(' var app = express();');
console.warn('');
return createApplication();
};
/**
* Expose the prototypes.
*/
exports.application = proto;
exports.request = req;
exports.response = res;
/**
* Expose constructors.
*/
exports.HTTPServer = HTTPServer;
exports.HTTPSServer = HTTPSServer;
exports.Route = Route;
/**
* View extensions.
*/
exports.View =
exports.view = require('./view');
/**
* Response extensions.
*/
require('./response');
/**
* Request extensions.
*/
require('./request');
exports.Router = Router;
// Error handler title

582
test/node_modules/express/lib/http.js generated vendored
View File

@@ -1,582 +0,0 @@
/*!
* Express - HTTPServer
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var qs = require('qs')
, connect = require('connect')
, router = require('./router')
, Router = require('./router')
, view = require('./view')
, toArray = require('./utils').toArray
, methods = router.methods.concat('del', 'all')
, url = require('url')
, utils = connect.utils;
/**
* Expose `HTTPServer`.
*/
exports = module.exports = HTTPServer;
/**
* Server proto.
*/
var app = HTTPServer.prototype;
/**
* Initialize a new `HTTPServer` with optional `middleware`.
*
* @param {Array} middleware
* @api public
*/
function HTTPServer(middleware){
connect.HTTPServer.call(this, []);
this.init(middleware);
};
/**
* Inherit from `connect.HTTPServer`.
*/
app.__proto__ = connect.HTTPServer.prototype;
/**
* Initialize the server.
*
* @param {Array} middleware
* @api private
*/
app.init = function(middleware){
var self = this;
this.cache = {};
this.settings = {};
this.redirects = {};
this.isCallbacks = {};
this._locals = {};
this.dynamicViewHelpers = {};
this.errorHandlers = [];
this.set('env', process.env.NODE_ENV || 'development');
// expose objects to each other
this.use(function(req, res, next){
req.query = req.query || {};
res.setHeader('X-Powered-By', 'Express');
req.app = res.app = self;
req.res = res;
res.req = req;
req.next = next;
// assign req.query
if (req.url.indexOf('?') > 0) {
var query = url.parse(req.url).query;
req.query = qs.parse(query);
}
next();
});
// apply middleware
if (middleware) middleware.forEach(self.use.bind(self));
// router
this.routes = new Router(this);
this.__defineGetter__('router', function(){
this.__usedRouter = true;
return self.routes.middleware;
});
// default locals
this.locals({
settings: this.settings
, app: this
});
// default development configuration
this.configure('development', function(){
this.enable('hints');
});
// default production configuration
this.configure('production', function(){
this.enable('view cache');
});
// register error handlers on "listening"
// so that they disregard definition position.
this.on('listening', this.registerErrorHandlers.bind(this));
// route manipulation methods
methods.forEach(function(method){
self.lookup[method] = function(path){
return self.routes.lookup(method, path);
};
self.match[method] = function(path){
return self.routes.match(method, path);
};
self.remove[method] = function(path){
return self.routes.lookup(method, path).remove();
};
});
// del -> delete
self.lookup.del = self.lookup.delete;
self.match.del = self.match.delete;
self.remove.del = self.remove.delete;
};
/**
* Remove routes matching the given `path`.
*
* @param {Route} path
* @return {Boolean}
* @api public
*/
app.remove = function(path){
return this.routes.lookup('all', path).remove();
};
/**
* Lookup routes defined with a path
* equivalent to `path`.
*
* @param {Stirng} path
* @return {Array}
* @api public
*/
app.lookup = function(path){
return this.routes.lookup('all', path);
};
/**
* Lookup routes matching the given `url`.
*
* @param {Stirng} url
* @return {Array}
* @api public
*/
app.match = function(url){
return this.routes.match('all', url);
};
/**
* When using the vhost() middleware register error handlers.
*/
app.onvhost = function(){
this.registerErrorHandlers();
};
/**
* Register error handlers.
*
* @return {Server} for chaining
* @api public
*/
app.registerErrorHandlers = function(){
this.errorHandlers.forEach(function(fn){
this.use(function(err, req, res, next){
fn.apply(this, arguments);
});
}, this);
return this;
};
/**
* Proxy `connect.HTTPServer#use()` to apply settings to
* mounted applications.
*
* @param {String|Function|Server} route
* @param {Function|Server} middleware
* @return {Server} for chaining
* @api public
*/
app.use = function(route, middleware){
var app, base, handle;
if ('string' != typeof route) {
middleware = route, route = '/';
}
// express app
if (middleware.handle && middleware.set) app = middleware;
// restore .app property on req and res
if (app) {
app.route = route;
middleware = function(req, res, next) {
var orig = req.app;
app.handle(req, res, function(err){
req.app = res.app = orig;
next(err);
});
};
}
connect.HTTPServer.prototype.use.call(this, route, middleware);
// mounted an app, invoke the hook
// and adjust some settings
if (app) {
base = this.set('basepath') || this.route;
if ('/' == base) base = '';
base = base + (app.set('basepath') || app.route);
app.set('basepath', base);
app.parent = this;
if (app.__mounted) app.__mounted.call(app, this);
}
return this;
};
/**
* Assign a callback `fn` which is called
* when this `Server` is passed to `Server#use()`.
*
* Examples:
*
* var app = express.createServer()
* , blog = express.createServer();
*
* blog.mounted(function(parent){
* // parent is app
* // "this" is blog
* });
*
* app.use(blog);
*
* @param {Function} fn
* @return {Server} for chaining
* @api public
*/
app.mounted = function(fn){
this.__mounted = fn;
return this;
};
/**
* See: view.register.
*
* @return {Server} for chaining
* @api public
*/
app.register = function(){
view.register.apply(this, arguments);
return this;
};
/**
* Register the given view helpers `obj`. This method
* can be called several times to apply additional helpers.
*
* @param {Object} obj
* @return {Server} for chaining
* @api public
*/
app.helpers =
app.locals = function(obj){
utils.merge(this._locals, obj);
return this;
};
/**
* Register the given dynamic view helpers `obj`. This method
* can be called several times to apply additional helpers.
*
* @param {Object} obj
* @return {Server} for chaining
* @api public
*/
app.dynamicHelpers = function(obj){
utils.merge(this.dynamicViewHelpers, obj);
return this;
};
/**
* Map the given param placeholder `name`(s) to the given callback(s).
*
* Param mapping is used to provide pre-conditions to routes
* which us normalized placeholders. This callback has the same
* signature as regular middleware, for example below when ":userId"
* is used this function will be invoked in an attempt to load the user.
*
* app.param('userId', function(req, res, next, id){
* User.find(id, function(err, user){
* if (err) {
* next(err);
* } else if (user) {
* req.user = user;
* next();
* } else {
* next(new Error('failed to load user'));
* }
* });
* });
*
* Passing a single function allows you to map logic
* to the values passed to `app.param()`, for example
* this is useful to provide coercion support in a concise manner.
*
* The following example maps regular expressions to param values
* ensuring that they match, otherwise passing control to the next
* route:
*
* app.param(function(name, regexp){
* if (regexp instanceof RegExp) {
* return function(req, res, next, val){
* var captures;
* if (captures = regexp.exec(String(val))) {
* req.params[name] = captures;
* next();
* } else {
* next('route');
* }
* }
* }
* });
*
* We can now use it as shown below, where "/commit/:commit" expects
* that the value for ":commit" is at 5 or more digits. The capture
* groups are then available as `req.params.commit` as we defined
* in the function above.
*
* app.param('commit', /^\d{5,}$/);
*
* For more of this useful functionality take a look
* at [express-params](http://github.com/visionmedia/express-params).
*
* @param {String|Array|Function} name
* @param {Function} fn
* @return {Server} for chaining
* @api public
*/
app.param = function(name, fn){
var self = this
, fns = [].slice.call(arguments, 1);
// array
if (Array.isArray(name)) {
name.forEach(function(name){
fns.forEach(function(fn){
self.param(name, fn);
});
});
// param logic
} else if ('function' == typeof name) {
this.routes.param(name);
// single
} else {
if (':' == name[0]) name = name.substr(1);
fns.forEach(function(fn){
self.routes.param(name, fn);
});
}
return this;
};
/**
* Assign a custom exception handler callback `fn`.
* These handlers are always _last_ in the middleware stack.
*
* @param {Function} fn
* @return {Server} for chaining
* @api public
*/
app.error = function(fn){
this.errorHandlers.push(fn);
return this;
};
/**
* Register the given callback `fn` for the given `type`.
*
* @param {String} type
* @param {Function} fn
* @return {Server} for chaining
* @api public
*/
app.is = function(type, fn){
if (!fn) return this.isCallbacks[type];
this.isCallbacks[type] = fn;
return this;
};
/**
* Assign `setting` to `val`, or return `setting`'s value.
* Mounted servers inherit their parent server's settings.
*
* @param {String} setting
* @param {String} val
* @return {Server|Mixed} for chaining, or the setting value
* @api public
*/
app.set = function(setting, val){
if (val === undefined) {
if (this.settings.hasOwnProperty(setting)) {
return this.settings[setting];
} else if (this.parent) {
return this.parent.set(setting);
}
} else {
this.settings[setting] = val;
return this;
}
};
/**
* Check if `setting` is enabled.
*
* @param {String} setting
* @return {Boolean}
* @api public
*/
app.enabled = function(setting){
return !!this.set(setting);
};
/**
* Check if `setting` is disabled.
*
* @param {String} setting
* @return {Boolean}
* @api public
*/
app.disabled = function(setting){
return !this.set(setting);
};
/**
* Enable `setting`.
*
* @param {String} setting
* @return {Server} for chaining
* @api public
*/
app.enable = function(setting){
return this.set(setting, true);
};
/**
* Disable `setting`.
*
* @param {String} setting
* @return {Server} for chaining
* @api public
*/
app.disable = function(setting){
return this.set(setting, false);
};
/**
* Redirect `key` to `url`.
*
* @param {String} key
* @param {String} url
* @return {Server} for chaining
* @api public
*/
app.redirect = function(key, url){
this.redirects[key] = url;
return this;
};
/**
* Configure callback for zero or more envs,
* when no env is specified that callback will
* be invoked for all environments. Any combination
* can be used multiple times, in any order desired.
*
* Examples:
*
* app.configure(function(){
* // executed for all envs
* });
*
* app.configure('stage', function(){
* // executed staging env
* });
*
* app.configure('stage', 'production', function(){
* // executed for stage and production
* });
*
* @param {String} env...
* @param {Function} fn
* @return {Server} for chaining
* @api public
*/
app.configure = function(env, fn){
var envs = 'all'
, args = toArray(arguments);
fn = args.pop();
if (args.length) envs = args;
if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);
return this;
};
/**
* Delegate `.VERB(...)` calls to `.route(VERB, ...)`.
*/
methods.forEach(function(method){
app[method] = function(path){
if (1 == arguments.length) return this.routes.lookup(method, path);
var args = [method].concat(toArray(arguments));
if (!this.__usedRouter) this.use(this.router);
return this.routes._route.apply(this.routes, args);
}
});
/**
* Special-cased "all" method, applying the given route `path`,
* middleware, and callback to _every_ HTTP method.
*
* @param {String} path
* @param {Function} ...
* @return {Server} for chaining
* @api public
*/
app.all = function(path){
var args = arguments;
if (1 == args.length) return this.routes.lookup('all', path);
methods.forEach(function(method){
if ('all' == method || 'del' == method) return;
app[method].apply(this, args);
}, this);
return this;
};
// del -> delete alias
app.del = app.delete;

View File

@@ -1,52 +0,0 @@
/*!
* Express - HTTPSServer
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var connect = require('connect')
, HTTPServer = require('./http')
, https = require('https');
/**
* Expose `HTTPSServer`.
*/
exports = module.exports = HTTPSServer;
/**
* Server proto.
*/
var app = HTTPSServer.prototype;
/**
* Initialize a new `HTTPSServer` with the
* given `options`, and optional `middleware`.
*
* @param {Object} options
* @param {Array} middleware
* @api public
*/
function HTTPSServer(options, middleware){
connect.HTTPSServer.call(this, options, []);
this.init(middleware);
};
/**
* Inherit from `connect.HTTPSServer`.
*/
app.__proto__ = connect.HTTPSServer.prototype;
// mixin HTTPServer methods
Object.keys(HTTPServer.prototype).forEach(function(method){
app[method] = HTTPServer.prototype[method];
});

33
test/node_modules/express/lib/middleware.js generated vendored Normal file
View File

@@ -0,0 +1,33 @@
/**
* Module dependencies.
*/
var utils = require('./utils');
/**
* Initialization middleware, exposing the
* request and response to eachother, as well
* as defaulting the X-Powered-By header field.
*
* @param {Function} app
* @return {Function}
* @api private
*/
exports.init = function(app){
return function expressInit(req, res, next){
req.app = res.app = app;
if (app.settings['x-powered-by']) res.setHeader('X-Powered-By', 'Express');
req.res = res;
res.req = req;
req.next = next;
req.__proto__ = app.request;
res.__proto__ = app.response;
res.locals = res.locals || utils.locals(res);
next();
}
};

View File

@@ -1,168 +1,248 @@
/*!
* Express - request
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var http = require('http')
, req = http.IncomingMessage.prototype
, utils = require('./utils')
, parse = require('url').parse
, mime = require('mime');
, connect = require('connect')
, fresh = require('fresh')
, parseRange = require('range-parser')
, parse = connect.utils.parseUrl
, mime = connect.mime;
/**
* Default flash formatters.
*
* @type Object
* Request prototype.
*/
var flashFormatters = exports.flashFormatters = {
s: function(val){
return String(val);
}
var req = exports = module.exports = {
__proto__: http.IncomingMessage.prototype
};
/**
* Return request header or optional default.
* Return request header.
*
* The `Referrer` header field is special-cased,
* both `Referrer` and `Referer` will yield are
* interchangeable.
* both `Referrer` and `Referer` are interchangeable.
*
* Examples:
*
* req.header('Content-Type');
* req.get('Content-Type');
* // => "text/plain"
*
* req.header('content-type');
* req.get('content-type');
* // => "text/plain"
*
* req.header('Accept');
* req.get('Something');
* // => undefined
*
* req.header('Accept', 'text/html');
* // => "text/html"
*
* Aliased as `req.header()`.
*
* @param {String} name
* @param {String} defaultValue
* @return {String}
* @api public
*/
req.header = function(name, defaultValue){
req.get =
req.header = function(name){
switch (name = name.toLowerCase()) {
case 'referer':
case 'referrer':
return this.headers.referrer
|| this.headers.referer
|| defaultValue;
|| this.headers.referer;
default:
return this.headers[name] || defaultValue;
return this.headers[name];
}
};
/**
* Get `field`'s `param` value, defaulting to ''.
* Check if the given `type(s)` is acceptable, returning
* the best match when true, otherwise `undefined`, in which
* case you should respond with 406 "Not Acceptable".
*
* Examples:
*
* req.get('content-disposition', 'filename');
* // => "something.png"
*
* @param {String} field
* @param {String} param
* @return {String}
* @api public
*/
req.get = function(field, param){
var val = this.header(field);
if (!val) return '';
var regexp = new RegExp(param + ' *= *(?:"([^"]+)"|([^;]+))', 'i');
if (!regexp.exec(val)) return '';
return RegExp.$1 || RegExp.$2;
};
/**
* Short-hand for `require('url').parse(req.url).pathname`.
*
* @return {String}
* @api public
*/
req.__defineGetter__('path', function(){
return parse(this.url).pathname;
});
/**
* Check if the _Accept_ header is present, and includes the given `type`.
*
* When the _Accept_ header is not present `true` is returned. Otherwise
* the given `type` is matched by an exact match, and then subtypes. You
* may pass the subtype such as "html" which is then converted internally
* to "text/html" using the mime lookup table.
* The `type` value may be a single mime type string
* such as "application/json", the extension name
* such as "json", a comma-delimted list such as "json, html, text/plain",
* or an array `["json", "html", "text/plain"]`. When a list
* or array is given the _best_ match, if any is returned.
*
* Examples:
*
* // Accept: text/html
* req.accepts('html');
* // => true
* // => "html"
*
* // Accept: text/*; application/json
* // Accept: text/*, application/json
* req.accepts('html');
* // => "html"
* req.accepts('text/html');
* req.accepts('text/plain');
* // => "text/html"
* req.accepts('json, text');
* // => "json"
* req.accepts('application/json');
* // => true
* // => "application/json"
*
* // Accept: text/*, application/json
* req.accepts('image/png');
* req.accepts('png');
* // => false
* // => undefined
*
* @param {String} type
* @return {Boolean}
* // Accept: text/*;q=.5, application/json
* req.accepts(['html', 'json']);
* req.accepts('html, json');
* // => "json"
*
* @param {String|Array} type(s)
* @return {String}
* @api public
*/
req.accepts = function(type){
var accept = this.header('Accept');
// normalize extensions ".json" -> "json"
if (type && '.' == type[0]) type = type.substr(1);
// when Accept does not exist, or contains '*/*' return true
if (!accept || ~accept.indexOf('*/*')) {
return true;
} else if (type) {
// allow "html" vs "text/html" etc
if (!~type.indexOf('/')) type = mime.lookup(type);
// check if we have a direct match
if (~accept.indexOf(type)) return true;
// check if we have type/*
type = type.split('/')[0] + '/*';
return !!~accept.indexOf(type);
} else {
return false;
}
return utils.accepts(type, this.get('Accept'));
};
/**
* Check if the given `charset` is acceptable,
* otherwise you should respond with 406 "Not Acceptable".
*
* @param {String} charset
* @return {Boolean}
* @api public
*/
req.acceptsCharset = function(charset){
var accepted = this.acceptedCharsets;
return accepted.length
? ~accepted.indexOf(charset)
: true;
};
/**
* Check if the given `lang` is acceptable,
* otherwise you should respond with 406 "Not Acceptable".
*
* @param {String} lang
* @return {Boolean}
* @api public
*/
req.acceptsLanguage = function(lang){
var accepted = this.acceptedLanguages;
return accepted.length
? ~accepted.indexOf(lang)
: true;
};
/**
* Parse Range header field,
* capping to the given `size`.
*
* Unspecified ranges such as "0-" require
* knowledge of your resource length. In
* the case of a byte range this is of course
* the total number of bytes. If the Range
* header field is not given `null` is returned,
* `-1` when unsatisfiable, `-2` when syntactically invalid.
*
* NOTE: remember that ranges are inclusive, so
* for example "Range: users=0-3" should respond
* with 4 users when available, not 3.
*
* @param {Number} size
* @return {Array}
* @api public
*/
req.range = function(size){
var range = this.get('Range');
if (!range) return;
return parseRange(size, range);
};
/**
* Return an array of Accepted media types
* ordered from highest quality to lowest.
*
* Examples:
*
* [ { value: 'application/json',
* quality: 1,
* type: 'application',
* subtype: 'json' },
* { value: 'text/html',
* quality: 0.5,
* type: 'text',
* subtype: 'html' } ]
*
* @return {Array}
* @api public
*/
req.__defineGetter__('accepted', function(){
var accept = this.get('Accept');
return accept
? utils.parseAccept(accept)
: [];
});
/**
* Return an array of Accepted languages
* ordered from highest quality to lowest.
*
* Examples:
*
* Accept-Language: en;q=.5, en-us
* ['en-us', 'en']
*
* @return {Array}
* @api public
*/
req.__defineGetter__('acceptedLanguages', function(){
var accept = this.get('Accept-Language');
return accept
? utils
.parseQuality(accept)
.map(function(obj){
return obj.value;
})
: [];
});
/**
* Return an array of Accepted charsets
* ordered from highest quality to lowest.
*
* Examples:
*
* Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8
* ['unicode-1-1', 'iso-8859-5']
*
* @return {Array}
* @api public
*/
req.__defineGetter__('acceptedCharsets', function(){
var accept = this.get('Accept-Charset');
return accept
? utils
.parseQuality(accept)
.map(function(obj){
return obj.value;
})
: [];
});
/**
* Return the value of param `name` when present or `defaultValue`.
*
* - Checks route placeholders, ex: _/user/:id_
* - Checks body params, ex: id=12, {"id":12}
* - Checks query string params, ex: ?id=12
* - Checks urlencoded body params, ex: id=12
*
* To utilize urlencoded request bodies, `req.body`
* To utilize request bodies, `req.body`
* should be an object. This can be done by using
* the `connect.bodyParser` middleware.
* the `connect.bodyParser()` middleware.
*
* @param {String} name
* @param {Mixed} defaultValue
@@ -171,80 +251,15 @@ req.accepts = function(type){
*/
req.param = function(name, defaultValue){
// route params like /user/:id
if (this.params && this.params.hasOwnProperty(name) && undefined !== this.params[name]) {
return this.params[name];
}
// query string params
if (undefined !== this.query[name]) {
return this.query[name];
}
// request body params via connect.bodyParser
if (this.body && undefined !== this.body[name]) {
return this.body[name];
}
var params = this.params || {};
var body = this.body || {};
var query = this.query || {};
if (null != params[name] && params.hasOwnProperty(name)) return params[name];
if (null != body[name]) return body[name];
if (null != query[name]) return query[name];
return defaultValue;
};
/**
* Queue flash `msg` of the given `type`.
*
* Examples:
*
* req.flash('info', 'email sent');
* req.flash('error', 'email delivery failed');
* req.flash('info', 'email re-sent');
* // => 2
*
* req.flash('info');
* // => ['email sent', 'email re-sent']
*
* req.flash('info');
* // => []
*
* req.flash();
* // => { error: ['email delivery failed'], info: [] }
*
* Formatting:
*
* Flash notifications also support arbitrary formatting support.
* For example you may pass variable arguments to `req.flash()`
* and use the %s specifier to be replaced by the associated argument:
*
* req.flash('info', 'email has been sent to %s.', userName);
*
* To add custom formatters use the `exports.flashFormatters` object.
*
* @param {String} type
* @param {String} msg
* @return {Array|Object|Number}
* @api public
*/
req.flash = function(type, msg){
if (this.session === undefined) throw Error('req.flash() requires sessions');
var msgs = this.session.flash = this.session.flash || {};
if (type && msg) {
var i = 2
, args = arguments
, formatters = this.app.flashFormatters || {};
formatters.__proto__ = flashFormatters;
msg = utils.miniMarkdown(msg);
msg = msg.replace(/%([a-zA-Z])/g, function(_, format){
var formatter = formatters[format];
if (formatter) return formatter(utils.escape(args[i++]));
});
return (msgs[type] = msgs[type] || []).push(msg);
} else if (type) {
var arr = msgs[type];
delete msgs[type];
return arr || [];
} else {
this.session.flash = {};
return msgs;
}
};
/**
* Check if the incoming request contains the "Content-Type"
* header field, and it contains the give mime `type`.
@@ -254,45 +269,25 @@ req.flash = function(type, msg){
* // With Content-Type: text/html; charset=utf-8
* req.is('html');
* req.is('text/html');
* req.is('text/*');
* // => true
*
* // When Content-Type is application/json
* req.is('json');
* req.is('application/json');
* req.is('application/*');
* // => true
*
* req.is('html');
* // => false
*
* Ad-hoc callbacks can also be registered with Express, to perform
* assertions again the request, for example if we need an expressive
* way to check if our incoming request is an image, we can register "an image"
* callback:
*
* app.is('an image', function(req){
* return 0 == req.headers['content-type'].indexOf('image');
* });
*
* Now within our route callbacks, we can use to to assert content types
* such as "image/jpeg", "image/png", etc.
*
* app.post('/image/upload', function(req, res, next){
* if (req.is('an image')) {
* // do something
* } else {
* next();
* }
* });
*
* @param {String} type
* @return {Boolean}
* @api public
*/
req.is = function(type){
var fn = this.app.is(type);
if (fn) return fn(this);
var ct = this.headers['content-type'];
var ct = this.get('Content-Type');
if (!ct) return false;
ct = ct.split(';')[0];
if (!~type.indexOf('/')) type = mime.lookup(type);
@@ -306,22 +301,6 @@ req.is = function(type){
return !! ~ct.indexOf(type);
};
// Callback for isXMLHttpRequest / xhr
function isxhr() {
return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';
}
/**
* Check if the request was an _XMLHttpRequest_.
*
* @return {Boolean}
* @api public
*/
req.__defineGetter__('isXMLHttpRequest', isxhr);
req.__defineGetter__('xhr', isxhr);
/**
* Return the protocol string "http" or "https"
* when requested with TLS. When the "trust proxy"
@@ -335,11 +314,11 @@ req.__defineGetter__('xhr', isxhr);
*/
req.__defineGetter__('protocol', function(){
var trustProxy = this.app.set('trust proxy');
var trustProxy = this.app.get('trust proxy');
return this.connection.encrypted
? 'https'
: trustProxy
? (this.header('X-Forwarded-Proto') || 'http')
? (this.get('X-Forwarded-Proto') || 'http')
: 'http';
});
@@ -354,4 +333,154 @@ req.__defineGetter__('protocol', function(){
req.__defineGetter__('secure', function(){
return 'https' == this.protocol;
});
});
/**
* Return the remote address, or when
* "trust proxy" is `true` return
* the upstream addr.
*
* @return {String}
* @api public
*/
req.__defineGetter__('ip', function(){
return this.ips[0] || this.connection.remoteAddress;
});
/**
* When "trust proxy" is `true`, parse
* the "X-Forwarded-For" ip address list.
*
* For example if the value were "client, proxy1, proxy2"
* you would receive the array `["client", "proxy1", "proxy2"]`
* where "proxy2" is the furthest down-stream.
*
* @return {Array}
* @api public
*/
req.__defineGetter__('ips', function(){
var trustProxy = this.app.get('trust proxy');
var val = this.get('X-Forwarded-For');
return trustProxy && val
? val.split(/ *, */)
: [];
});
/**
* Return basic auth credentials.
*
* Examples:
*
* // http://tobi:hello@example.com
* req.auth
* // => { username: 'tobi', password: 'hello' }
*
* @return {Object} or undefined
* @api public
*/
req.__defineGetter__('auth', function(){
// missing
var auth = this.get('Authorization');
if (!auth) return;
// malformed
var parts = auth.split(' ');
if ('basic' != parts[0].toLowerCase()) return;
if (!parts[1]) return;
auth = parts[1];
// credentials
auth = new Buffer(auth, 'base64').toString().split(':');
return { username: auth[0], password: auth[1] };
});
/**
* Return subdomains as an array.
*
* For example "tobi.ferrets.example.com"
* would provide `["ferrets", "tobi"]`.
*
* @return {Array}
* @api public
*/
req.__defineGetter__('subdomains', function(){
return this.get('Host')
.split('.')
.slice(0, -2)
.reverse();
});
/**
* Short-hand for `url.parse(req.url).pathname`.
*
* @return {String}
* @api public
*/
req.__defineGetter__('path', function(){
return parse(this).pathname;
});
/**
* Parse the "Host" header field hostname.
*
* @return {String}
* @api public
*/
req.__defineGetter__('host', function(){
return this.get('Host').split(':')[0];
});
/**
* Check if the request is fresh, aka
* Last-Modified and/or the ETag
* still match.
*
* @return {Boolean}
* @api public
*/
req.__defineGetter__('fresh', function(){
var method = this.method;
var s = this.res.statusCode;
// GET or HEAD for weak freshness validation only
if ('GET' != method && 'HEAD' != method) return false;
// 2xx or 304 as per rfc2616 14.26
if ((s >= 200 && s < 300) || 304 == s) {
return fresh(this.headers, this.res._headers);
}
return false;
});
/**
* Check if the request is stale, aka
* "Last-Modified" and / or the "ETag" for the
* resource has changed.
*
* @return {Boolean}
* @api public
*/
req.__defineGetter__('stale', function(){
return !this.fresh;
});
/**
* Check if the request was an _XMLHttpRequest_.
*
* @return {Boolean}
* @api public
*/
req.__defineGetter__('xhr', function(){
var val = this.get('X-Requested-With') || '';
return 'xmlhttprequest' == val.toLowerCase();
});

View File

@@ -1,145 +1,29 @@
/*!
* Express - response
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var fs = require('fs')
, http = require('http')
var http = require('http')
, path = require('path')
, connect = require('connect')
, utils = connect.utils
, parseRange = require('./utils').parseRange
, res = http.ServerResponse.prototype
, send = connect.static.send
, mime = require('mime')
, sign = require('cookie-signature').sign
, normalizeType = require('./utils').normalizeType
, normalizeTypes = require('./utils').normalizeTypes
, etag = require('./utils').etag
, statusCodes = http.STATUS_CODES
, cookie = require('cookie')
, send = require('send')
, mime = connect.mime
, basename = path.basename
, extname = path.extname
, join = path.join;
/**
* Send a response with the given `body` and optional `headers` and `status` code.
*
* Examples:
*
* res.send();
* res.send(new Buffer('wahoo'));
* res.send({ some: 'json' });
* res.send('<p>some html</p>');
* res.send('Sorry, cant find that', 404);
* res.send('text', { 'Content-Type': 'text/plain' }, 201);
* res.send(404);
*
* @param {String|Object|Number|Buffer} body or status
* @param {Object|Number} headers or status
* @param {Number} status
* @return {ServerResponse}
* @api public
* Response prototype.
*/
res.send = function(body, headers, status){
// allow status as second arg
if ('number' == typeof headers) {
status = headers,
headers = null;
}
// default status
status = status || this.statusCode;
// allow 0 args as 204
if (!arguments.length || undefined === body) status = 204;
// determine content type
switch (typeof body) {
case 'number':
if (!this.header('Content-Type')) {
this.contentType('.txt');
}
body = http.STATUS_CODES[status = body];
break;
case 'string':
if (!this.header('Content-Type')) {
this.charset = this.charset || 'utf-8';
this.contentType('.html');
}
break;
case 'boolean':
case 'object':
if (Buffer.isBuffer(body)) {
if (!this.header('Content-Type')) {
this.contentType('.bin');
}
} else {
return this.json(body, headers, status);
}
break;
}
// populate Content-Length
if (undefined !== body && !this.header('Content-Length')) {
this.header('Content-Length', Buffer.isBuffer(body)
? body.length
: Buffer.byteLength(body));
}
// merge headers passed
if (headers) {
var fields = Object.keys(headers);
for (var i = 0, len = fields.length; i < len; ++i) {
var field = fields[i];
this.header(field, headers[field]);
}
}
// strip irrelevant headers
if (204 == status || 304 == status) {
this.removeHeader('Content-Type');
this.removeHeader('Content-Length');
body = '';
}
// respond
this.statusCode = status;
this.end('HEAD' == this.req.method ? null : body);
return this;
};
/**
* Send JSON response with `obj`, optional `headers`, and optional `status`.
*
* Examples:
*
* res.json(null);
* res.json({ user: 'tj' });
* res.json('oh noes!', 500);
* res.json('I dont have that', 404);
*
* @param {Mixed} obj
* @param {Object|Number} headers or status
* @param {Number} status
* @return {ServerResponse}
* @api public
*/
res.json = function(obj, headers, status){
var body = JSON.stringify(obj)
, callback = this.req.query.callback
, jsonp = this.app.enabled('jsonp callback');
this.charset = this.charset || 'utf-8';
this.header('Content-Type', 'application/json');
if (callback && jsonp) {
this.header('Content-Type', 'text/javascript');
body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';
}
return this.send(body, headers, status);
var res = module.exports = {
__proto__: http.ServerResponse.prototype
};
/**
@@ -156,15 +40,242 @@ res.status = function(code){
};
/**
* Transfer the file at the given `path`. Automatically sets
* the _Content-Type_ response header field. `next()` is called
* when `path` is a directory, or when an error occurs.
* Set Link header field with the given `links`.
*
* Examples:
*
* res.links({
* next: 'http://api.example.com/users?page=2',
* last: 'http://api.example.com/users?page=5'
* });
*
* @param {Object} links
* @return {ServerResponse}
* @api public
*/
res.links = function(links){
return this.set('Link', Object.keys(links).map(function(rel){
return '<' + links[rel] + '>; rel="' + rel + '"';
}).join(', '));
};
/**
* Send a response.
*
* Examples:
*
* res.send(new Buffer('wahoo'));
* res.send({ some: 'json' });
* res.send('<p>some html</p>');
* res.send(404, 'Sorry, cant find that');
* res.send(404);
*
* @param {Mixed} body or status
* @param {Mixed} body
* @return {ServerResponse}
* @api public
*/
res.send = function(body){
var req = this.req
, head = 'HEAD' == req.method
, len;
// allow status / body
if (2 == arguments.length) {
// res.send(body, status) backwards compat
if ('number' != typeof body && 'number' == typeof arguments[1]) {
this.statusCode = arguments[1];
} else {
this.statusCode = body;
body = arguments[1];
}
}
switch (typeof body) {
// response status
case 'number':
this.get('Content-Type') || this.type('txt');
this.statusCode = body;
body = http.STATUS_CODES[body];
break;
// string defaulting to html
case 'string':
if (!this.get('Content-Type')) {
this.charset = this.charset || 'utf-8';
this.type('html');
}
break;
case 'boolean':
case 'object':
if (null == body) {
body = '';
} else if (Buffer.isBuffer(body)) {
this.get('Content-Type') || this.type('bin');
} else {
return this.json(body);
}
break;
}
// populate Content-Length
if (undefined !== body && !this.get('Content-Length')) {
this.set('Content-Length', len = Buffer.isBuffer(body)
? body.length
: Buffer.byteLength(body));
}
// ETag support
// TODO: W/ support
if (len > 1024) {
if (!this.get('ETag')) {
this.set('ETag', etag(body));
}
}
// freshness
if (req.fresh) this.statusCode = 304;
// strip irrelevant headers
if (204 == this.statusCode || 304 == this.statusCode) {
this.removeHeader('Content-Type');
this.removeHeader('Content-Length');
this.removeHeader('Transfer-Encoding');
body = '';
}
// respond
this.end(head ? null : body);
return this;
};
/**
* Send JSON response.
*
* Examples:
*
* res.json(null);
* res.json({ user: 'tj' });
* res.json(500, 'oh noes!');
* res.json(404, 'I dont have that');
*
* @param {Mixed} obj or status
* @param {Mixed} obj
* @return {ServerResponse}
* @api public
*/
res.json = function(obj){
// allow status / body
if (2 == arguments.length) {
// res.json(body, status) backwards compat
if ('number' == typeof arguments[1]) {
this.statusCode = arguments[1];
} else {
this.statusCode = obj;
obj = arguments[1];
}
}
// settings
var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);
// content-type
this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');
return this.send(body);
};
/**
* Send JSON response with JSONP callback support.
*
* Examples:
*
* res.jsonp(null);
* res.jsonp({ user: 'tj' });
* res.jsonp(500, 'oh noes!');
* res.jsonp(404, 'I dont have that');
*
* @param {Mixed} obj or status
* @param {Mixed} obj
* @return {ServerResponse}
* @api public
*/
res.jsonp = function(obj){
// allow status / body
if (2 == arguments.length) {
// res.json(body, status) backwards compat
if ('number' == typeof arguments[1]) {
this.statusCode = arguments[1];
} else {
this.statusCode = obj;
obj = arguments[1];
}
}
// settings
var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
var callback = this.req.query[app.get('jsonp callback name')];
// content-type
this.charset = this.charset || 'utf-8';
this.set('Content-Type', 'application/json');
// jsonp
if (callback) {
this.set('Content-Type', 'text/javascript');
var cb = callback.replace(/[^\[\]\w$.]/g, '');
body = cb + ' && ' + cb + '(' + body + ');';
}
return this.send(body);
};
/**
* Transfer the file at the given `path`.
*
* Automatically sets the _Content-Type_ response header field.
* The callback `fn(err)` is invoked when the transfer is complete
* or when an error occurs. Be sure to check `res.sentHeader`
* if you wish to attempt responding, as the header and some data
* may have already been transferred.
*
* Options:
*
* - `maxAge` defaulting to 0
* - `root` root directory for relative filenames
*
* Examples:
*
* The following example illustrates how `res.sendfile()` may
* be used as an alternative for the `static()` middleware for
* dynamic situations. The code backing `res.sendfile()` is actually
* the same code, so HTTP cache support etc is identical.
*
* app.get('/user/:uid/photos/:file', function(req, res){
* var uid = req.params.uid
* , file = req.params.file;
*
* req.user.mayViewFilesFrom(uid, function(yes){
* if (yes) {
* res.sendfile('/uploads/' + uid + '/' + file);
* } else {
* res.send(403, 'Sorry! you cant see that.');
* }
* });
* });
*
* @param {String} path
* @param {Object|Function} options or fn
* @param {Function} fn
@@ -172,8 +283,11 @@ res.status = function(code){
*/
res.sendfile = function(path, options, fn){
var next = this.req.next;
options = options || {};
var self = this
, req = self.req
, next = this.req.next
, options = options || {}
, done;
// support function as second arg
if ('function' == typeof options) {
@@ -181,32 +295,185 @@ res.sendfile = function(path, options, fn){
options = {};
}
options.path = encodeURIComponent(path);
options.callback = fn;
send(this.req, this, next, options);
// socket errors
req.socket.on('error', error);
// errors
function error(err) {
if (done) return;
done = true;
// clean up
cleanup();
if (!self.headerSent) self.removeHeader('Content-Disposition');
// callback available
if (fn) return fn(err);
// list in limbo if there's no callback
if (self.headerSent) return;
// delegate
next(err);
}
// streaming
function stream() {
if (done) return;
cleanup();
if (fn) self.on('finish', fn);
}
// cleanup
function cleanup() {
req.socket.removeListener('error', error);
}
// transfer
var file = send(req, path);
if (options.root) file.root(options.root);
file.maxage(options.maxAge || 0);
file.on('error', error);
file.on('directory', next);
file.on('stream', stream);
file.pipe(this);
this.on('finish', cleanup);
};
/**
* Set _Content-Type_ response header passed through `mime.lookup()`.
* Transfer the file at the given `path` as an attachment.
*
* Examples:
* Optionally providing an alternate attachment `filename`,
* and optional callback `fn(err)`. The callback is invoked
* when the data transfer is complete, or when an error has
* ocurred. Be sure to check `res.headerSent` if you plan to respond.
*
* var filename = 'path/to/image.png';
* res.contentType(filename);
* // res.headers['Content-Type'] is now "image/png"
* This method uses `res.sendfile()`.
*
* res.contentType('.html');
* res.contentType('html');
* res.contentType('json');
* res.contentType('png');
*
* @param {String} type
* @return {String} the resolved mime type
* @param {String} path
* @param {String|Function} filename or fn
* @param {Function} fn
* @api public
*/
res.contentType = function(type){
return this.header('Content-Type', mime.lookup(type));
res.download = function(path, filename, fn){
// support function as second arg
if ('function' == typeof filename) {
fn = filename;
filename = null;
}
filename = filename || path;
this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"');
return this.sendfile(path, fn);
};
/**
* Set _Content-Type_ response header with `type` through `mime.lookup()`
* when it does not contain "/", or set the Content-Type to `type` otherwise.
*
* Examples:
*
* res.type('.html');
* res.type('html');
* res.type('json');
* res.type('application/json');
* res.type('png');
*
* @param {String} type
* @return {ServerResponse} for chaining
* @api public
*/
res.contentType =
res.type = function(type){
return this.set('Content-Type', ~type.indexOf('/')
? type
: mime.lookup(type));
};
/**
* Respond to the Acceptable formats using an `obj`
* of mime-type callbacks.
*
* This method uses `req.accepted`, an array of
* acceptable types ordered by their quality values.
* When "Accept" is not present the _first_ callback
* is invoked, otherwise the first match is used. When
* no match is performed the server responds with
* 406 "Not Acceptable".
*
* Content-Type is set for you, however if you choose
* you may alter this within the callback using `res.type()`
* or `res.set('Content-Type', ...)`.
*
* res.format({
* 'text/plain': function(){
* res.send('hey');
* },
*
* 'text/html': function(){
* res.send('<p>hey</p>');
* },
*
* 'appliation/json': function(){
* res.send({ message: 'hey' });
* }
* });
*
* In addition to canonicalized MIME types you may
* also use extnames mapped to these types:
*
* res.format({
* text: function(){
* res.send('hey');
* },
*
* html: function(){
* res.send('<p>hey</p>');
* },
*
* json: function(){
* res.send({ message: 'hey' });
* }
* });
*
* By default Express passes an `Error`
* with a `.status` of 406 to `next(err)`
* if a match is not made. If you provide
* a `.default` callback it will be invoked
* instead.
*
* @param {Object} obj
* @return {ServerResponse} for chaining
* @api public
*/
res.format = function(obj){
var req = this.req
, next = req.next;
var fn = obj.default;
if (fn) delete obj.default;
var keys = Object.keys(obj);
var key = req.accepts(keys);
this.set('Vary', 'Accept');
if (key) {
this.set('Content-Type', normalizeType(key));
obj[key](req, this, next);
} else if (fn) {
fn();
} else {
var err = new Error('Not Acceptable');
err.status = 406;
err.types = normalizeTypes(keys);
next(err);
}
return this;
};
/**
@@ -218,81 +485,67 @@ res.contentType = function(type){
*/
res.attachment = function(filename){
if (filename) this.contentType(filename);
this.header('Content-Disposition', filename
if (filename) this.type(extname(filename));
this.set('Content-Disposition', filename
? 'attachment; filename="' + basename(filename) + '"'
: 'attachment');
return this;
};
/**
* Transfer the file at the given `path`, with optional
* `filename` as an attachment and optional callback `fn(err)`,
* and optional `fn2(err)` which is invoked when an error has
* occurred after header has been sent.
* Set header `field` to `val`, or pass
* an object of header fields.
*
* @param {String} path
* @param {String|Function} filename or fn
* @param {Function} fn
* @param {Function} fn2
* @api public
*/
res.download = function(path, filename, fn, fn2){
var self = this;
// support callback as second arg
if ('function' == typeof filename) {
fn2 = fn;
fn = filename;
filename = null;
}
// transfer the file
this.attachment(filename || path).sendfile(path, function(err){
var sentHeader = self._header;
if (err) {
if (!sentHeader) self.removeHeader('Content-Disposition');
if (sentHeader) {
fn2 && fn2(err);
} else if (fn) {
fn(err);
} else {
self.req.next(err);
}
} else if (fn) {
fn();
}
});
};
/**
* Set or get response header `name` with optional `val`.
* Examples:
*
* @param {String} name
* res.set('Accept', 'application/json');
* res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
*
* Aliased as `res.header()`.
*
* @param {String|Object} field
* @param {String} val
* @return {ServerResponse} for chaining
* @api public
*/
res.header = function(name, val){
if (1 == arguments.length) return this.getHeader(name);
this.setHeader(name, val);
res.set =
res.header = function(field, val){
if (2 == arguments.length) {
this.setHeader(field, '' + val);
} else {
for (var key in field) {
this.setHeader(key, '' + field[key]);
}
}
return this;
};
/**
* Get value for header `field`.
*
* @param {String} field
* @return {String}
* @api public
*/
res.get = function(field){
return this.getHeader(field);
};
/**
* Clear cookie `name`.
*
* @param {String} name
* @param {Object} options
* @param {ServerResponse} for chaining
* @api public
*/
res.clearCookie = function(name, options){
var opts = { expires: new Date(1) };
this.cookie(name, '', options
? utils.merge(options, opts)
var opts = { expires: new Date(1), path: '/' };
return this.cookie(name, '', options
? utils.merge(opts, options)
: opts);
};
@@ -302,7 +555,8 @@ res.clearCookie = function(name, options){
* Options:
*
* - `maxAge` max-age in milliseconds, converted to `expires`
* - `path` defaults to the "basepath" setting which is typically "/"
* - `signed` sign the cookie
* - `path` defaults to "/"
*
* Examples:
*
@@ -313,147 +567,156 @@ res.clearCookie = function(name, options){
* res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
*
* @param {String} name
* @param {String} val
* @param {String|Object} val
* @param {Options} options
* @api public
*/
res.cookie = function(name, val, options){
options = options || {};
if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);
if (undefined === options.path) options.path = this.app.set('basepath');
var cookie = utils.serializeCookie(name, val, options);
this.header('Set-Cookie', cookie);
options = utils.merge({}, options);
var secret = this.req.secret;
var signed = options.signed;
if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');
if ('object' == typeof val) val = 'j:' + JSON.stringify(val);
if (signed) val = 's:' + sign(val, secret);
if ('maxAge' in options) {
options.expires = new Date(Date.now() + options.maxAge);
options.maxAge /= 1000;
}
if (null == options.path) options.path = '/';
this.set('Set-Cookie', cookie.serialize(name, String(val), options));
return this;
};
/**
* Redirect to the given `url` with optional response `status`
* defauling to 302.
* defaulting to 302.
*
* The given `url` can also be the name of a mapped url, for
* example by default express supports "back" which redirects
* to the _Referrer_ or _Referer_ headers or the application's
* "basepath" setting. Express also supports "basepath" out of the box,
* which can be set via `app.set('basepath', '/blog');`, and defaults
* to '/'.
* to the _Referrer_ or _Referer_ headers or "/".
*
* Redirect Mapping:
*
* To extend the redirect mapping capabilities that Express provides,
* we may use the `app.redirect()` method:
*
* app.redirect('google', 'http://google.com');
*
* Now in a route we may call:
* Examples:
*
* res.redirect('google');
* res.redirect('/foo/bar');
* res.redirect('http://example.com');
* res.redirect(301, 'http://example.com');
* res.redirect('http://example.com', 301);
* res.redirect('../login'); // /blog/post/1 -> /blog/login
*
* We may also map dynamic redirects:
* Mounting:
*
* app.redirect('comments', function(req, res){
* return '/post/' + req.params.id + '/comments';
* });
* When an application is mounted, and `res.redirect()`
* is given a path that does _not_ lead with "/". For
* example suppose a "blog" app is mounted at "/blog",
* the following redirect would result in "/blog/login":
*
* So now we may do the following, and the redirect will dynamically adjust to
* the context of the request. If we called this route with _GET /post/12_ our
* redirect _Location_ would be _/post/12/comments_.
* res.redirect('login');
*
* app.get('/post/:id', function(req, res){
* res.redirect('comments');
* });
* While the leading slash would result in a redirect to "/login":
*
* Unless an absolute `url` is given, the app's mount-point
* will be respected. For example if we redirect to `/posts`,
* and our app is mounted at `/blog` we will redirect to `/blog/posts`.
* res.redirect('/login');
*
* @param {String} url
* @param {Number} code
* @api public
*/
res.redirect = function(url, status){
res.redirect = function(url){
var app = this.app
, req = this.req
, base = app.set('basepath') || app.route
, status = status || 302
, head = 'HEAD' == req.method
, status = 302
, body;
// Setup redirect map
var map = {
back: req.header('Referrer', base)
, home: base
};
// allow status / url
if (2 == arguments.length) {
if ('number' == typeof url) {
status = url;
url = arguments[1];
} else {
status = arguments[1];
}
}
// Support custom redirect map
map.__proto__ = app.redirects;
// setup redirect map
var map = { back: req.get('Referrer') || '/' };
// Attempt mapped redirect
var mapped = 'function' == typeof map[url]
? map[url](req, this)
: map[url];
// perform redirect
url = map[url] || url;
// Perform redirect
url = mapped || url;
// relative
if (!~url.indexOf('://') && 0 != url.indexOf('//')) {
var path = app.path();
// Relative
if (!~url.indexOf('://')) {
// Respect mount-point
if ('/' != base && 0 != url.indexOf(base)) url = base + url;
// Absolute
var host = req.headers.host;
url = req.protocol + '://' + host + url;
// relative to path
if ('.' == url[0]) {
url = req.path + '/' + url;
// relative to mount-point
} else if ('/' != url[0]) {
url = path + '/' + url;
}
}
// Support text/{plain,html} by default
if (req.accepts('html')) {
body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';
this.header('Content-Type', 'text/html');
} else {
body = http.STATUS_CODES[status] + '. Redirecting to ' + url;
this.header('Content-Type', 'text/plain');
}
this.format({
text: function(){
body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);
},
html: function(){
var u = utils.escape(url);
body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';
},
default: function(){
body = '';
}
});
// Respond
this.statusCode = status;
this.header('Location', url);
this.set('Location', url);
this.set('Content-Length', Buffer.byteLength(body));
this.end(head ? null : body);
};
/**
* Assign the view local variable `name` to `val` or return the
* local previously assigned to `name`.
* Render `view` with the given `options` and optional callback `fn`.
* When a callback function is given a response will _not_ be made
* automatically, otherwise a response of _200_ and _text/html_ is given.
*
* @param {String} name
* @param {Mixed} val
* @return {Mixed} val
* Options:
*
* - `cache` boolean hinting to the engine it should cache
* - `filename` filename of the view being rendered
*
* @param {String} view
* @param {Object|Function} options or callback function
* @param {Function} fn
* @api public
*/
res.local = function(name, val){
this._locals = this._locals || {};
return undefined === val
? this._locals[name]
: this._locals[name] = val;
};
res.render = function(view, options, fn){
var self = this
, options = options || {}
, req = this.req
, app = req.app;
/**
* Assign several locals with the given `obj`,
* or return the locals.
*
* @param {Object} obj
* @return {Object|Undefined}
* @api public
*/
res.locals =
res.helpers = function(obj){
if (obj) {
for (var key in obj) {
this.local(key, obj[key]);
}
} else {
return this._locals;
// support callback function as second arg
if ('function' == typeof options) {
fn = options, options = {};
}
// merge res.locals
options._locals = self.locals;
// default callback to respond
fn = fn || function(err, str){
if (err) return req.next(err);
self.send(str);
};
// render
app.render(view, options, fn);
};

View File

@@ -1,53 +0,0 @@
/*!
* Express - router - Collection
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Expose `Collection`.
*/
module.exports = Collection;
/**
* Initialize a new route `Collection`
* with the given `router`.
*
* @param {Router} router
* @api private
*/
function Collection(router) {
Array.apply(this, arguments);
this.router = router;
}
/**
* Inherit from `Array.prototype`.
*/
Collection.prototype.__proto__ = Array.prototype;
/**
* Remove the routes in this collection.
*
* @return {Collection} of routes removed
* @api public
*/
Collection.prototype.remove = function(){
var router = this.router
, len = this.length
, ret = new Collection(this.router);
for (var i = 0; i < len; ++i) {
if (router.remove(this[i])) {
ret.push(this[i]);
}
}
return ret;
};

View File

@@ -1,19 +1,12 @@
/*!
* Express - Router
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Route = require('./route')
, Collection = require('./collection')
, utils = require('../utils')
, parse = require('url').parse
, toArray = utils.toArray;
, methods = require('methods')
, debug = require('debug')('express:router')
, parse = require('connect').utils.parseUrl;
/**
* Expose `Router` constructor.
@@ -22,26 +15,21 @@ var Route = require('./route')
exports = module.exports = Router;
/**
* Expose HTTP methods.
*/
var methods = exports.methods = require('./methods');
/**
* Initialize a new `Router` with the given `app`.
*
* @param {express.HTTPServer} app
* Initialize a new `Router` with the given `options`.
*
* @param {Object} options
* @api private
*/
function Router(app) {
function Router(options) {
options = options || {};
var self = this;
this.app = app;
this.routes = {};
this.map = {};
this.params = {};
this._params = [];
this.middleware = function(req, res, next){
this.caseSensitive = options.caseSensitive;
this.strict = options.strict;
this.middleware = function router(req, res, next){
self._dispatch(req, res, next);
};
}
@@ -83,104 +71,6 @@ Router.prototype.param = function(name, fn){
return this;
};
/**
* Return a `Collection` of all routes defined.
*
* @return {Collection}
* @api public
*/
Router.prototype.all = function(){
return this.find(function(){
return true;
});
};
/**
* Remove the given `route`, returns
* a bool indicating if the route was present
* or not.
*
* @param {Route} route
* @return {Boolean}
* @api public
*/
Router.prototype.remove = function(route){
var routes = this.routes[route.method]
, len = routes.length;
for (var i = 0; i < len; ++i) {
if (route == routes[i]) {
routes.splice(i, 1);
return true;
}
}
};
/**
* Return routes with route paths matching `path`.
*
* @param {String} method
* @param {String} path
* @return {Collection}
* @api public
*/
Router.prototype.lookup = function(method, path){
return this.find(function(route){
return path == route.path
&& (route.method == method
|| method == 'all');
});
};
/**
* Return routes with regexps that match the given `url`.
*
* @param {String} method
* @param {String} url
* @return {Collection}
* @api public
*/
Router.prototype.match = function(method, url){
return this.find(function(route){
return route.match(url)
&& (route.method == method
|| method == 'all');
});
};
/**
* Find routes based on the return value of `fn`
* which is invoked once per route.
*
* @param {Function} fn
* @return {Collection}
* @api public
*/
Router.prototype.find = function(fn){
var len = methods.length
, ret = new Collection(this)
, method
, routes
, route;
for (var i = 0; i < len; ++i) {
method = methods[i];
routes = this.routes[method];
if (!routes) continue;
for (var j = 0, jlen = routes.length; j < jlen; ++j) {
route = routes[j];
if (fn(route)) ret.push(route);
}
}
return ret;
};
/**
* Route dispatcher aka the route "middleware".
*
@@ -194,6 +84,8 @@ Router.prototype._dispatch = function(req, res, next){
var params = this.params
, self = this;
debug('dispatching %s %s (%s)', req.method, req.url, req.originalUrl);
// route dispatch
(function pass(i, err){
var paramCallbacks
@@ -201,8 +93,7 @@ Router.prototype._dispatch = function(req, res, next){
, paramVal
, route
, keys
, key
, ret;
, key;
// match next route
function nextRoute(err) {
@@ -210,13 +101,11 @@ Router.prototype._dispatch = function(req, res, next){
}
// match route
req.route = route = self._match(req, i);
// implied OPTIONS
if (!route && 'OPTIONS' == req.method) return self._options(req, res);
req.route = route = self.matchRequest(req, i);
// no route
if (!route) return next(err);
debug('matched %s %s', route.method, route.path);
// we have a route
// start at param 0
@@ -251,7 +140,7 @@ Router.prototype._dispatch = function(req, res, next){
};
param(err);
// single param callbacks
function paramCallback(err) {
var fn = paramCallbacks[paramIndex++];
@@ -269,7 +158,8 @@ Router.prototype._dispatch = function(req, res, next){
if (fn.length < 4) return callbacks(err);
fn(err, req, res, callbacks);
} else if (fn) {
fn(req, res, callbacks);
if (fn.length < 4) return fn(req, res, callbacks);
callbacks();
} else {
nextRoute(err);
}
@@ -280,44 +170,10 @@ Router.prototype._dispatch = function(req, res, next){
})(0);
};
/**
* Respond to __OPTIONS__ method.
*
* @param {IncomingMessage} req
* @param {ServerResponse} res
* @api private
*/
Router.prototype._options = function(req, res){
var path = parse(req.url).pathname
, body = this._optionsFor(path).join(',');
res.send(body, { Allow: body });
};
/**
* Return an array of HTTP verbs or "options" for `path`.
*
* @param {String} path
* @return {Array}
* @api private
*/
Router.prototype._optionsFor = function(path){
var self = this;
return methods.filter(function(method){
var routes = self.routes[method];
if (!routes || 'options' == method) return;
for (var i = 0, len = routes.length; i < len; ++i) {
if (routes[i].match(path)) return true;
}
}).map(function(method){
return method.toUpperCase();
});
};
/**
* Attempt to match a route for `req`
* starting from offset `i`.
* with optional starting index of `i`
* defaulting to 0.
*
* @param {IncomingMessage} req
* @param {Number} i
@@ -325,17 +181,20 @@ Router.prototype._optionsFor = function(path){
* @api private
*/
Router.prototype._match = function(req, i){
Router.prototype.matchRequest = function(req, i, head){
var method = req.method.toLowerCase()
, url = parse(req.url)
, url = parse(req)
, path = url.pathname
, routes = this.routes
, captures
, route
, keys;
, routes = this.map
, i = i || 0
, route;
// pass HEAD to GET routes
if ('head' == method) method = 'get';
// HEAD support
if (!head && 'head' == method) {
route = this.matchRequest(req, i, true);
if (route) return route;
method = 'get';
}
// routes for this method
if (routes = routes[method]) {
@@ -343,24 +202,7 @@ Router.prototype._match = function(req, i){
// matching routes
for (var len = routes.length; i < len; ++i) {
route = routes[i];
if (captures = route.match(path)) {
keys = route.keys;
route.params = [];
// params from capture groups
for (var j = 1, jlen = captures.length; j < jlen; ++j) {
var key = keys[j-1]
, val = 'string' == typeof captures[j]
? decodeURIComponent(captures[j])
: captures[j];
if (key) {
route.params[key.name] = val;
} else {
route.params.push(val);
}
}
// all done
if (route.match(path)) {
req._route_index = i;
return route;
}
@@ -368,6 +210,23 @@ Router.prototype._match = function(req, i){
}
};
/**
* Attempt to match a route for `method`
* and `url` with optional starting
* index of `i` defaulting to 0.
*
* @param {String} method
* @param {String} url
* @param {Number} i
* @return {Route}
* @api private
*/
Router.prototype.match = function(method, url, i, head){
var req = { method: method, url: url };
return this.matchRequest(req, i, head);
};
/**
* Route `method`, `path`, and one or more callbacks.
*
@@ -378,21 +237,37 @@ Router.prototype._match = function(req, i){
* @api private
*/
Router.prototype._route = function(method, path, callbacks){
var app = this.app
, callbacks = utils.flatten(toArray(arguments, 2));
Router.prototype.route = function(method, path, callbacks){
var method = method.toLowerCase()
, callbacks = utils.flatten([].slice.call(arguments, 2));
// ensure path was given
if (!path) throw new Error('app.' + method + '() requires a path');
if (!path) throw new Error('Router#' + method + '() requires a path');
// ensure all callbacks are functions
callbacks.forEach(function(fn, i){
if ('function' == typeof fn) return;
var type = {}.toString.call(fn);
var msg = '.' + method + '() requires callback functions but got a ' + type;
throw new Error(msg);
});
// create the route
debug('defined %s %s', method, path);
var route = new Route(method, path, callbacks, {
sensitive: app.enabled('case sensitive routes')
, strict: app.enabled('strict routing')
sensitive: this.caseSensitive,
strict: this.strict
});
// add it
(this.routes[method] = this.routes[method] || [])
.push(route);
(this.map[method] = this.map[method] || []).push(route);
return this;
};
methods.forEach(function(method){
Router.prototype[method] = function(path){
var args = [method].concat([].slice.call(arguments));
this.route.apply(this, args);
return this;
};
});

View File

@@ -1,79 +0,0 @@
/*!
* Express - router - methods
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Hypertext Transfer Protocol -- HTTP/1.1
* http://www.ietf.org/rfc/rfc2616.txt
*/
var RFC2616 = ['OPTIONS', 'GET', 'POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT'];
/**
* HTTP Extensions for Distributed Authoring -- WEBDAV
* http://www.ietf.org/rfc/rfc2518.txt
*/
var RFC2518 = ['PROPFIND', 'PROPPATCH', 'MKCOL', 'COPY', 'MOVE', 'LOCK', 'UNLOCK'];
/**
* Versioning Extensions to WebDAV
* http://www.ietf.org/rfc/rfc3253.txt
*/
var RFC3253 = ['VERSION-CONTROL', 'REPORT', 'CHECKOUT', 'CHECKIN', 'UNCHECKOUT', 'MKWORKSPACE', 'UPDATE', 'LABEL', 'MERGE', 'BASELINE-CONTROL', 'MKACTIVITY'];
/**
* Ordered Collections Protocol (WebDAV)
* http://www.ietf.org/rfc/rfc3648.txt
*/
var RFC3648 = ['ORDERPATCH'];
/**
* Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol
* http://www.ietf.org/rfc/rfc3744.txt
*/
var RFC3744 = ['ACL'];
/**
* Web Distributed Authoring and Versioning (WebDAV) SEARCH
* http://www.ietf.org/rfc/rfc5323.txt
*/
var RFC5323 = ['SEARCH'];
/**
* PATCH Method for HTTP
* http://www.ietf.org/rfc/rfc5789.txt
*/
var RFC5789 = ['PATCH'];
/**
* PURGE Method for caching reverse-proxy
* http://wiki.squid-cache.org/SquidFaq/OperatingSquid#How_can_I_purge_an_object_from_my_cache.3F
* https://www.varnish-cache.org/docs/trunk/tutorial/purging.html
*/
var CACHE_PURGE = ['PURGE'];
/**
* Expose the methods.
*/
module.exports = [].concat(
RFC2616
, RFC2518
, RFC3253
, RFC3648
, RFC3744
, RFC5323
, RFC5789
, CACHE_PURGE).map(function(method){
return method.toLowerCase();
});

View File

@@ -1,10 +1,10 @@
/*!
* Express - router - Route
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
/**
* Module dependencies.
*/
var utils = require('../utils');
/**
* Expose `Route`.
*/
@@ -32,57 +32,41 @@ function Route(method, path, callbacks, options) {
this.path = path;
this.method = method;
this.callbacks = callbacks;
this.regexp = normalize(path
this.regexp = utils.pathRegexp(path
, this.keys = []
, options.sensitive
, options.strict);
}
/**
* Check if this route matches `path` and return captures made.
* Check if this route matches `path`, if so
* populate `.params`.
*
* @param {String} path
* @return {Array}
* @return {Boolean}
* @api private
*/
Route.prototype.match = function(path){
return this.regexp.exec(path);
var keys = this.keys
, params = this.params = []
, m = this.regexp.exec(path);
if (!m) return false;
for (var i = 1, len = m.length; i < len; ++i) {
var key = keys[i - 1];
var val = 'string' == typeof m[i]
? decodeURIComponent(m[i])
: m[i];
if (key) {
params[key.name] = val;
} else {
params.push(val);
}
}
return true;
};
/**
* Normalize the given path string,
* returning a regular expression.
*
* An empty array should be passed,
* which will contain the placeholder
* key names. For example "/user/:id" will
* then contain ["id"].
*
* @param {String|RegExp} path
* @param {Array} keys
* @param {Boolean} sensitive
* @param {Boolean} strict
* @return {RegExp}
* @api private
*/
function normalize(path, keys, sensitive, strict) {
if (path instanceof RegExp) return path;
path = path
.concat(strict ? '' : '/?')
.replace(/\/\(/g, '(?:/')
.replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional){
keys.push({ name: key, optional: !! optional });
slash = slash || '';
return ''
+ (optional ? '' : slash)
+ '(?:'
+ (optional ? slash : '')
+ (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'
+ (optional || '');
})
.replace(/([\/.])/g, '\\$1')
.replace(/\*/g, '(.*)');
return new RegExp('^' + path + '$', sensitive ? '' : 'i');
}

View File

@@ -1,10 +1,44 @@
/*!
* Express - Utils
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
/**
* Module dependencies.
*/
var mime = require('connect').mime
, crc32 = require('buffer-crc32');
/**
* Return ETag for `body`.
*
* @param {String|Buffer} body
* @return {String}
* @api private
*/
exports.etag = function(body){
return '"' + crc32.signed(body) + '"';
};
/**
* Make `locals()` bound to the given `obj`.
*
* This is used for `app.locals` and `res.locals`.
*
* @param {Object} obj
* @return {Function}
* @api private
*/
exports.locals = function(obj){
obj.viewCallbacks = obj.viewCallbacks || [];
function locals(obj){
for (var key in obj) locals[key] = obj[key];
return obj;
};
return locals;
};
/**
* Check if `path` looks absolute.
*
@@ -18,31 +52,6 @@ exports.isAbsolute = function(path){
if (':' == path[1] && '\\' == path[2]) return true;
};
/**
* Merge object `b` with `a` giving precedence to
* values in object `a`.
*
* @param {Object} a
* @param {Object} b
* @return {Object} a
* @api private
*/
exports.union = function(a, b){
if (a && b) {
var keys = Object.keys(b)
, len = keys.length
, key;
for (var i = 0; i < len; ++i) {
key = keys[i];
if (!a.hasOwnProperty(key)) {
a[key] = b[key];
}
}
}
return a;
};
/**
* Flatten the given `arr`.
*
@@ -65,26 +74,158 @@ exports.flatten = function(arr, ret){
};
/**
* Parse mini markdown implementation.
* The following conversions are supported,
* primarily for the "flash" middleware:
* Normalize the given `type`, for example "html" becomes "text/html".
*
* _foo_ or *foo* become <em>foo</em>
* __foo__ or **foo** become <strong>foo</strong>
* [A](B) becomes <a href="B">A</a>
* @param {String} type
* @return {String}
* @api private
*/
exports.normalizeType = function(type){
return ~type.indexOf('/') ? type : mime.lookup(type);
};
/**
* Normalize `types`, for example "html" becomes "text/html".
*
* @param {Array} types
* @return {Array}
* @api private
*/
exports.normalizeTypes = function(types){
var ret = [];
for (var i = 0; i < types.length; ++i) {
ret.push(~types[i].indexOf('/')
? types[i]
: mime.lookup(types[i]));
}
return ret;
};
/**
* Return the acceptable type in `types`, if any.
*
* @param {Array} types
* @param {String} str
* @return {String}
* @api private
*/
exports.miniMarkdown = function(str){
return String(str)
.replace(/(__|\*\*)(.*?)\1/g, '<strong>$2</strong>')
.replace(/(_|\*)(.*?)\1/g, '<em>$2</em>')
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
exports.acceptsArray = function(types, str){
// accept anything when Accept is not present
if (!str) return types[0];
// parse
var accepted = exports.parseAccept(str)
, normalized = exports.normalizeTypes(types)
, len = accepted.length;
for (var i = 0; i < len; ++i) {
for (var j = 0, jlen = types.length; j < jlen; ++j) {
if (exports.accept(normalized[j].split('/'), accepted[i])) {
return types[j];
}
}
}
};
/**
* Check if `type(s)` are acceptable based on
* the given `str`.
*
* @param {String|Array} type(s)
* @param {String} str
* @return {Boolean|String}
* @api private
*/
exports.accepts = function(type, str){
if ('string' == typeof type) type = type.split(/ *, */);
return exports.acceptsArray(type, str);
};
/**
* Check if `type` array is acceptable for `other`.
*
* @param {Array} type
* @param {Object} other
* @return {Boolean}
* @api private
*/
exports.accept = function(type, other){
return (type[0] == other.type || '*' == other.type)
&& (type[1] == other.subtype || '*' == other.subtype);
};
/**
* Parse accept `str`, returning
* an array objects containing
* `.type` and `.subtype` along
* with the values provided by
* `parseQuality()`.
*
* @param {Type} name
* @return {Type}
* @api private
*/
exports.parseAccept = function(str){
return exports
.parseQuality(str)
.map(function(obj){
var parts = obj.value.split('/');
obj.type = parts[0];
obj.subtype = parts[1];
return obj;
});
};
/**
* Parse quality `str`, returning an
* array of objects with `.value` and
* `.quality`.
*
* @param {Type} name
* @return {Type}
* @api private
*/
exports.parseQuality = function(str){
return str
.split(/ *, */)
.map(quality)
.filter(function(obj){
return obj.quality;
})
.sort(function(a, b){
return b.quality - a.quality;
});
};
/**
* Parse quality `str` returning an
* object with `.value` and `.quality`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function quality(str) {
var parts = str.split(/ *; */)
, val = parts[0];
var q = parts[1]
? parseFloat(parts[1].split(/ *= */)[1])
: 1;
return { value: val, quality: q };
}
/**
* Escape special characters in the given string of html.
*
@@ -102,51 +243,40 @@ exports.escape = function(html) {
};
/**
* Parse "Range" header `str` relative to the given file `size`.
* Normalize the given path string,
* returning a regular expression.
*
* @param {Number} size
* @param {String} str
* @return {Array}
* An empty array should be passed,
* which will contain the placeholder
* key names. For example "/user/:id" will
* then contain ["id"].
*
* @param {String|RegExp|Array} path
* @param {Array} keys
* @param {Boolean} sensitive
* @param {Boolean} strict
* @return {RegExp}
* @api private
*/
exports.parseRange = function(size, str){
var valid = true;
var arr = str.substr(6).split(',').map(function(range){
var range = range.split('-')
, start = parseInt(range[0], 10)
, end = parseInt(range[1], 10);
// -500
if (isNaN(start)) {
start = size - end;
end = size - 1;
// 500-
} else if (isNaN(end)) {
end = size - 1;
}
// Invalid
if (isNaN(start) || isNaN(end) || start > end) valid = false;
return { start: start, end: end };
});
return valid ? arr : undefined;
};
/**
* Fast alternative to `Array.prototype.slice.call()`.
*
* @param {Arguments} args
* @param {Number} n
* @return {Array}
* @api public
*/
exports.toArray = function(args, i){
var arr = []
, len = args.length
, i = i || 0;
for (; i < len; ++i) arr.push(args[i]);
return arr;
};
exports.pathRegexp = function(path, keys, sensitive, strict) {
if (path instanceof RegExp) return path;
if (Array.isArray(path)) path = '(' + path.join('|') + ')';
path = path
.concat(strict ? '' : '/?')
.replace(/\/\(/g, '(?:/')
.replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){
keys.push({ name: key, optional: !! optional });
slash = slash || '';
return ''
+ (optional ? '' : slash)
+ '(?:'
+ (optional ? slash : '')
+ (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'
+ (optional || '')
+ (star ? '(/*)?' : '');
})
.replace(/([\/.])/g, '\\$1')
.replace(/\*/g, '(.*)');
return new RegExp('^' + path + '$', sensitive ? '' : 'i');
}

480
test/node_modules/express/lib/view.js generated vendored
View File

@@ -1,460 +1,76 @@
/*!
* Express - view
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var path = require('path')
, extname = path.extname
, fs = require('fs')
, utils = require('./utils')
, dirname = path.dirname
, basename = path.basename
, utils = require('connect').utils
, View = require('./view/view')
, partial = require('./view/partial')
, union = require('./utils').union
, merge = utils.merge
, http = require('http')
, res = http.ServerResponse.prototype;
, extname = path.extname
, exists = fs.existsSync || path.existsSync
, join = path.join;
/**
* Expose constructors.
* Expose `View`.
*/
exports = module.exports = View;
module.exports = View;
/**
* Export template engine registrar.
*/
exports.register = View.register;
/**
* Lookup and compile `view` with cache support by supplying
* both the `cache` object and `cid` string,
* followed by `options` passed to `exports.lookup()`.
*
* @param {String} view
* @param {Object} cache
* @param {Object} cid
* @param {Object} options
* @return {View}
* @api private
*/
exports.compile = function(view, cache, cid, options){
if (cache && cid && cache[cid]){
options.filename = cache[cid].path;
return cache[cid];
}
// lookup
view = exports.lookup(view, options);
// hints
if (!view.exists) {
if (options.hint) hintAtViewPaths(view.original, options);
var err = new Error('failed to locate view "' + view.original.view + '"');
err.view = view.original;
throw err;
}
// compile
options.filename = view.path;
view.fn = view.templateEngine.compile(view.contents, options);
cache[cid] = view;
return view;
};
/**
* Lookup `view`, returning an instanceof `View`.
* Initialize a new `View` with the given `name`.
*
* Options:
*
* - `root` root directory path
* - `defaultEngine` default template engine
* - `parentView` parent `View` object
* - `cache` cache object
* - `cacheid` optional cache id
* - `defaultEngine` the default template engine name
* - `engines` template engine require() cache
* - `root` root path for view lookup
*
* Lookup:
*
* - partial `_<name>`
* - any `<name>/index`
* - non-layout `../<name>/index`
* - any `<root>/<name>`
* - partial `<root>/_<name>`
*
* @param {String} view
* @param {String} name
* @param {Object} options
* @return {View}
* @api private
*/
exports.lookup = function(view, options){
var orig = view = new View(view, options)
, partial = options.isPartial
, layout = options.isLayout;
// Try _ prefix ex: ./views/_<name>.jade
// taking precedence over the direct path
if (partial) {
view = new View(orig.prefixPath, options);
if (!view.exists) view = orig;
}
// Try index ex: ./views/user/index.jade
if (!layout && !view.exists) view = new View(orig.indexPath, options);
// Try ../<name>/index ex: ../user/index.jade
// when calling partial('user') within the same dir
if (!layout && !view.exists) view = new View(orig.upIndexPath, options);
// Try root ex: <root>/user.jade
if (!view.exists) view = new View(orig.rootPath, options);
// Try root _ prefix ex: <root>/_user.jade
if (!view.exists && partial) view = new View(view.prefixPath, options);
view.original = orig;
return view;
};
function View(name, options) {
options = options || {};
this.name = name;
this.root = options.root;
var engines = options.engines;
this.defaultEngine = options.defaultEngine;
var ext = this.ext = extname(name);
if (!ext) name += (ext = this.ext = '.' + this.defaultEngine);
this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
this.path = this.lookup(name);
}
/**
* Partial render helper.
* Lookup view by the given `path`
*
* @api private
*/
function renderPartial(res, view, options, parentLocals, parent){
var collection, object, locals;
if (options) {
// collection
if (options.collection) {
collection = options.collection;
delete options.collection;
} else if ('length' in options) {
collection = options;
options = {};
}
// locals
if (options.locals) {
locals = options.locals;
delete options.locals;
}
// object
if ('Object' != options.constructor.name) {
object = options;
options = {};
} else if (undefined != options.object) {
object = options.object;
delete options.object;
}
} else {
options = {};
}
// Inherit locals from parent
union(options, parentLocals);
// Merge locals
if (locals) merge(options, locals);
// Partials dont need layouts
options.isPartial = true;
options.layout = false;
// Deduce name from view path
var name = options.as || partial.resolveObjectName(view);
// Render partial
function render(){
if (object) {
if ('string' == typeof name) {
options[name] = object;
} else if (name === global) {
merge(options, object);
}
}
return res.render(view, options, null, parent, true);
}
// Collection support
if (collection) {
var len = collection.length
, buf = ''
, keys
, key
, val;
options.collectionLength = len;
if ('number' == typeof len || Array.isArray(collection)) {
for (var i = 0; i < len; ++i) {
val = collection[i];
options.firstInCollection = i == 0;
options.indexInCollection = i;
options.lastInCollection = i == len - 1;
object = val;
buf += render();
}
} else {
keys = Object.keys(collection);
len = keys.length;
options.collectionLength = len;
options.collectionKeys = keys;
for (var i = 0; i < len; ++i) {
key = keys[i];
val = collection[key];
options.keyInCollection = key;
options.firstInCollection = i == 0;
options.indexInCollection = i;
options.lastInCollection = i == len - 1;
object = val;
buf += render();
}
}
return buf;
} else {
return render();
}
};
/**
* Render `view` partial with the given `options`. Optionally a
* callback `fn(err, str)` may be passed instead of writing to
* the socket.
*
* Options:
*
* - `object` Single object with name derived from the view (unless `as` is present)
*
* - `as` Variable name for each `collection` value, defaults to the view name.
* * as: 'something' will add the `something` local variable
* * as: this will use the collection value as the template context
* * as: global will merge the collection value's properties with `locals`
*
* - `collection` Array of objects, the name is derived from the view name itself.
* For example _video.html_ will have a object _video_ available to it.
*
* @param {String} view
* @param {Object|Array|Function} options, collection, callback, or object
* @param {Function} fn
* @param {String} path
* @return {String}
* @api public
*/
res.partial = function(view, options, fn){
var app = this.app
, options = options || {}
, viewEngine = app.set('view engine')
, parent = {};
// accept callback as second argument
if ('function' == typeof options) {
fn = options;
options = {};
}
// root "views" option
parent.dirname = app.set('views') || process.cwd() + '/views';
// utilize "view engine" option
if (viewEngine) parent.engine = viewEngine;
// render the partial
try {
var str = renderPartial(this, view, options, null, parent);
} catch (err) {
if (fn) {
fn(err);
} else {
this.req.next(err);
}
return;
}
// callback or transfer
if (fn) {
fn(null, str);
} else {
this.send(str);
}
};
/**
* Render `view` with the given `options` and optional callback `fn`.
* When a callback function is given a response will _not_ be made
* automatically, however otherwise a response of _200_ and _text/html_ is given.
*
* Options:
*
* - `scope` Template evaluation context (the value of `this`)
* - `debug` Output debugging information
* - `status` Response status code
*
* @param {String} view
* @param {Object|Function} options or callback function
* @param {Function} fn
* @api public
*/
res.render = function(view, opts, fn, parent, sub){
// support callback function as second arg
if ('function' == typeof opts) {
fn = opts, opts = null;
}
try {
return this._render(view, opts, fn, parent, sub);
} catch (err) {
// callback given
if (fn) {
fn(err);
// unwind to root call to prevent multiple callbacks
} else if (sub) {
throw err;
// root template, next(err)
} else {
this.req.next(err);
}
}
};
// private render()
res._render = function(view, opts, fn, parent, sub){
var options = {}
, self = this
, app = this.app
, helpers = app._locals
, dynamicHelpers = app.dynamicViewHelpers
, viewOptions = app.set('view options')
, root = app.set('views') || process.cwd() + '/views';
// cache id
var cid = app.enabled('view cache')
? view + (parent ? ':' + parent.path : '')
: false;
// merge "view options"
if (viewOptions) merge(options, viewOptions);
// merge res._locals
if (this._locals) merge(options, this._locals);
// merge render() options
if (opts) merge(options, opts);
// merge render() .locals
if (opts && opts.locals) merge(options, opts.locals);
// status support
if (options.status) this.statusCode = options.status;
// capture attempts
options.attempts = [];
var partial = options.isPartial
, layout = options.layout;
// Layout support
if (true === layout || undefined === layout) {
layout = 'layout';
}
// Default execution scope to a plain object
options.scope = options.scope || {};
// Populate view
options.parentView = parent;
// "views" setting
options.root = root;
// "view engine" setting
options.defaultEngine = app.set('view engine');
// charset option
if (options.charset) this.charset = options.charset;
// Dynamic helper support
if (false !== options.dynamicHelpers) {
// cache
if (!this.__dynamicHelpers) {
this.__dynamicHelpers = {};
for (var key in dynamicHelpers) {
this.__dynamicHelpers[key] = dynamicHelpers[key].call(
this.app
, this.req
, this);
}
}
// apply
merge(options, this.__dynamicHelpers);
}
// Merge view helpers
union(options, helpers);
// Always expose partial() as a local
options.partial = function(path, opts){
return renderPartial(self, path, opts, options, view);
};
// View lookup
options.hint = app.enabled('hints');
view = exports.compile(view, app.cache, cid, options);
// layout helper
options.layout = function(path){
layout = path;
};
// render
var str = view.fn.call(options.scope, options);
// layout expected
if (layout) {
options.isLayout = true;
options.layout = false;
options.body = str;
this.render(layout, options, fn, view, true);
// partial return
} else if (partial) {
return str;
// render complete, and
// callback given
} else if (fn) {
fn(null, str);
// respond
} else {
this.send(str);
}
}
/**
* Hint at view path resolution, outputting the
* paths that Express has tried.
*
* @api private
*/
function hintAtViewPaths(view, options) {
console.error();
console.error('failed to locate view "' + view.view + '", tried:');
options.attempts.forEach(function(path){
console.error(' - %s', path);
});
console.error();
}
View.prototype.lookup = function(path){
var ext = this.ext;
// <path>.<engine>
if (!utils.isAbsolute(path)) path = join(this.root, path);
if (exists(path)) return path;
// <path>/index.<engine>
path = join(dirname(path), basename(path, ext), 'index' + ext);
if (exists(path)) return path;
};
/**
* Render with the given `options` and callback `fn(err, str)`.
*
* @param {Object} options
* @param {Function} fn
* @api private
*/
View.prototype.render = function(options, fn){
this.engine(this.path, options, fn);
};

View File

@@ -1,40 +0,0 @@
/*!
* Express - view - Partial
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Memory cache.
*/
var cache = {};
/**
* Resolve partial object name from the view path.
*
* Examples:
*
* "user.ejs" becomes "user"
* "forum thread.ejs" becomes "forumThread"
* "forum/thread/post.ejs" becomes "post"
* "blog-post.ejs" becomes "blogPost"
*
* @return {String}
* @api private
*/
exports.resolveObjectName = function(view){
return cache[view] || (cache[view] = view
.split('/')
.slice(-1)[0]
.split('.')[0]
.replace(/^_/, '')
.replace(/[^a-zA-Z0-9 ]+/g, ' ')
.split(/ +/).map(function(word, i){
return i
? word[0].toUpperCase() + word.substr(1)
: word;
}).join(''));
};

View File

@@ -1,210 +0,0 @@
/*!
* Express - View
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var path = require('path')
, utils = require('../utils')
, extname = path.extname
, dirname = path.dirname
, basename = path.basename
, fs = require('fs')
, stat = fs.statSync;
/**
* Expose `View`.
*/
exports = module.exports = View;
/**
* Require cache.
*/
var cache = {};
/**
* Initialize a new `View` with the given `view` path and `options`.
*
* @param {String} view
* @param {Object} options
* @api private
*/
function View(view, options) {
options = options || {};
this.view = view;
this.root = options.root;
this.relative = false !== options.relative;
this.defaultEngine = options.defaultEngine;
this.parent = options.parentView;
this.basename = basename(view);
this.engine = this.resolveEngine();
this.extension = '.' + this.engine;
this.name = this.basename.replace(this.extension, '');
this.path = this.resolvePath();
this.dirname = dirname(this.path);
if (options.attempts) {
if (!~options.attempts.indexOf(this.path))
options.attempts.push(this.path);
}
};
/**
* Check if the view path exists.
*
* @return {Boolean}
* @api public
*/
View.prototype.__defineGetter__('exists', function(){
try {
stat(this.path);
return true;
} catch (err) {
return false;
}
});
/**
* Resolve view engine.
*
* @return {String}
* @api private
*/
View.prototype.resolveEngine = function(){
// Explicit
if (~this.basename.indexOf('.')) return extname(this.basename).substr(1);
// Inherit from parent
if (this.parent) return this.parent.engine;
// Default
return this.defaultEngine;
};
/**
* Resolve view path.
*
* @return {String}
* @api private
*/
View.prototype.resolvePath = function(){
var path = this.view;
// Implicit engine
if (!~this.basename.indexOf('.')) path += this.extension;
// Absolute
if (utils.isAbsolute(path)) return path;
// Relative to parent
if (this.relative && this.parent) return this.parent.dirname + '/' + path;
// Relative to root
return this.root
? this.root + '/' + path
: path;
};
/**
* Get view contents. This is a one-time hit, so we
* can afford to be sync.
*
* @return {String}
* @api public
*/
View.prototype.__defineGetter__('contents', function(){
return fs.readFileSync(this.path, 'utf8');
});
/**
* Get template engine api, cache exports to reduce
* require() calls.
*
* @return {Object}
* @api public
*/
View.prototype.__defineGetter__('templateEngine', function(){
var ext = this.extension;
return cache[ext] || (cache[ext] = require(this.engine));
});
/**
* Return root path alternative.
*
* @return {String}
* @api public
*/
View.prototype.__defineGetter__('rootPath', function(){
this.relative = false;
return this.resolvePath();
});
/**
* Return index path alternative.
*
* @return {String}
* @api public
*/
View.prototype.__defineGetter__('indexPath', function(){
return this.dirname
+ '/' + this.basename.replace(this.extension, '')
+ '/index' + this.extension;
});
/**
* Return ../<name>/index path alternative.
*
* @return {String}
* @api public
*/
View.prototype.__defineGetter__('upIndexPath', function(){
return this.dirname + '/../' + this.name + '/index' + this.extension;
});
/**
* Return _ prefix path alternative
*
* @return {String}
* @api public
*/
View.prototype.__defineGetter__('prefixPath', function(){
return this.dirname + '/_' + this.basename;
});
/**
* Register the given template engine `exports`
* as `ext`. For example we may wish to map ".html"
* files to jade:
*
* app.register('.html', require('jade'));
*
* or
*
* app.register('html', require('jade'));
*
* This is also useful for libraries that may not
* match extensions correctly. For example my haml.js
* library is installed from npm as "hamljs" so instead
* of layout.hamljs, we can register the engine as ".haml":
*
* app.register('.haml', require('haml-js'));
*
* @param {String} ext
* @param {Object} obj
* @api public
*/
exports.register = function(ext, exports) {
if ('.' != ext[0]) ext = '.' + ext;
cache[ext] = exports;
};

View File

@@ -0,0 +1 @@
node_modules

View File

@@ -0,0 +1,8 @@
language: node_js
node_js:
- 0.6
- 0.8
notifications:
email:
recipients:
- brianloveswords@gmail.com

View File

@@ -0,0 +1,33 @@
# buffer-crc32
[![Build Status](https://secure.travis-ci.org/brianloveswords/buffer-crc32.png?branch=master)](http://travis-ci.org/brianloveswords/buffer-crc32)
crc32 that works with binary data and fancy character sets, outputs
buffer, signed or unsigned data and has tests.
Derived from the sample CRC implementation in the PNG specification: http://www.w3.org/TR/PNG/#D-CRCAppendix
# install
```
npm install buffer-crc32
```
# example
```js
var crc32 = require('buffer-crc32');
// works with buffers
var buf = Buffer([[0x00, 0x73, 0x75, 0x70, 0x20, 0x62, 0x72, 0x6f, 0x00])
crc32(buf) // -> <Buffer 94 5a ab 4a>
// has convenience methods for getting signed or unsigned ints
crc32.signed(buf) // -> -1805997238
crc32.unsigned(buf) // -> 2488970058
// will cast to buffer if given a string, so you can
// directly use foreign characters safely
crc32('自動販売機') // -> <Buffer cb 03 1a c5>
```
# tests
This was tested against the output of zlib's crc32 method. You can run
the tests with`npm test` (requires tap)

View File

@@ -0,0 +1,84 @@
var Buffer = require('buffer').Buffer;
var CRC_TABLE = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
0x2d02ef8d
];
function bufferizeInt(num) {
var tmp = Buffer(4);
tmp.writeInt32BE(num, 0);
return tmp;
}
function _crc32(buf) {
if (!Buffer.isBuffer(buf))
buf = Buffer(buf);
var crc = 0xffffffff;
for (var n = 0; n < buf.length; n++) {
crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8);
}
return (crc ^ 0xffffffff);
}
function crc32() {
return bufferizeInt(_crc32.apply(null, arguments));
}
crc32.signed = function () {
return _crc32.apply(null, arguments);
};
crc32.unsigned = function () {
return crc32.apply(null, arguments).readUInt32BE(0);
};
module.exports = crc32;

View File

@@ -0,0 +1,36 @@
{
"author": {
"name": "Brian J. Brennan",
"email": "brianloveswords@gmail.com",
"url": "http://bjb.io"
},
"name": "buffer-crc32",
"description": "A pure javascript CRC32 algorithm that plays nice with binary data",
"version": "0.1.1",
"homepage": "https://github.com/brianloveswords/buffer-crc32",
"repository": {
"type": "git",
"url": "git://github.com/brianloveswords/buffer-crc32.git"
},
"main": "index.js",
"scripts": {
"test": "./node_modules/.bin/tap tests/*.test.js"
},
"dependencies": {},
"devDependencies": {
"tap": "~0.2.5"
},
"optionalDependencies": {},
"engines": {
"node": "*"
},
"_id": "buffer-crc32@0.1.1",
"_engineSupported": true,
"_npmVersion": "1.1.24",
"_nodeVersion": "v0.6.19",
"_defaultsLoaded": true,
"dist": {
"shasum": "738551e25072dd68d88417ad8a662650e33fe49c"
},
"_from": "buffer-crc32@0.1.1"
}

View File

@@ -0,0 +1,52 @@
var crc32 = require('..');
var test = require('tap').test;
test('simple crc32 is no problem', function (t) {
var input = Buffer('hey sup bros');
var expected = Buffer([0x47, 0xfa, 0x55, 0x70]);
t.same(crc32(input), expected);
t.end();
});
test('another simple one', function (t) {
var input = Buffer('IEND');
var expected = Buffer([0xae, 0x42, 0x60, 0x82]);
t.same(crc32(input), expected);
t.end();
});
test('slightly more complex', function (t) {
var input = Buffer([0x00, 0x00, 0x00]);
var expected = Buffer([0xff, 0x41, 0xd9, 0x12]);
t.same(crc32(input), expected);
t.end();
});
test('complex crc32 gets calculated like a champ', function (t) {
var input = Buffer('शीर्षक');
var expected = Buffer([0x17, 0xb8, 0xaf, 0xf1]);
t.same(crc32(input), expected);
t.end();
});
test('casts to buffer if necessary', function (t) {
var input = 'शीर्षक';
var expected = Buffer([0x17, 0xb8, 0xaf, 0xf1]);
t.same(crc32(input), expected);
t.end();
});
test('can do unsigned', function (t) {
var input = 'ham sandwich';
var expected = -1891873021;
t.same(crc32.signed(input), expected);
t.end();
});
test('can do signed', function (t) {
var input = 'bear sandwich';
var expected = 3711466352;
t.same(crc32.unsigned(input), expected);
t.end();
});

View File

@@ -0,0 +1,4 @@
support
test
examples
*.sock

View File

@@ -0,0 +1,4 @@
language: node_js
node_js:
- 0.4
- 0.6

View File

@@ -0,0 +1,107 @@
0.6.1 / 2012-06-01
==================
* Added: append (yes or no) on confirmation
* Added: allow node.js v0.7.x
0.6.0 / 2012-04-10
==================
* Added `.prompt(obj, callback)` support. Closes #49
* Added default support to .choose(). Closes #41
* Fixed the choice example
0.5.1 / 2011-12-20
==================
* Fixed `password()` for recent nodes. Closes #36
0.5.0 / 2011-12-04
==================
* Added sub-command option support [itay]
0.4.3 / 2011-12-04
==================
* Fixed custom help ordering. Closes #32
0.4.2 / 2011-11-24
==================
* Added travis support
* Fixed: line-buffered input automatically trimmed. Closes #31
0.4.1 / 2011-11-18
==================
* Removed listening for "close" on --help
0.4.0 / 2011-11-15
==================
* Added support for `--`. Closes #24
0.3.3 / 2011-11-14
==================
* Fixed: wait for close event when writing help info [Jerry Hamlet]
0.3.2 / 2011-11-01
==================
* Fixed long flag definitions with values [felixge]
0.3.1 / 2011-10-31
==================
* Changed `--version` short flag to `-V` from `-v`
* Changed `.version()` so it's configurable [felixge]
0.3.0 / 2011-10-31
==================
* Added support for long flags only. Closes #18
0.2.1 / 2011-10-24
==================
* "node": ">= 0.4.x < 0.7.0". Closes #20
0.2.0 / 2011-09-26
==================
* Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs]
0.1.0 / 2011-08-24
==================
* Added support for custom `--help` output
0.0.5 / 2011-08-18
==================
* Changed: when the user enters nothing prompt for password again
* Fixed issue with passwords beginning with numbers [NuckChorris]
0.0.4 / 2011-08-15
==================
* Fixed `Commander#args`
0.0.3 / 2011-08-15
==================
* Added default option value support
0.0.2 / 2011-08-15
==================
* Added mask support to `Command#password(str[, mask], fn)`
* Added `Command#password(str, fn)`
0.0.1 / 2010-01-03
==================
* Initial release

View File

@@ -0,0 +1,7 @@
TESTS = $(shell find test/test.*.js)
test:
@./test/run $(TESTS)
.PHONY: test

View File

@@ -0,0 +1,262 @@
# Commander.js
The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander).
[![Build Status](https://secure.travis-ci.org/visionmedia/commander.js.png)](http://travis-ci.org/visionmedia/commander.js)
## Installation
$ npm install commander
## Option parsing
Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.0.1')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);
console.log('you ordered a pizza with:');
if (program.peppers) console.log(' - peppers');
if (program.pineapple) console.log(' - pineappe');
if (program.bbq) console.log(' - bbq');
console.log(' - %s cheese', program.cheese);
```
Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.
## Automated --help
The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
```
$ ./examples/pizza --help
Usage: pizza [options]
Options:
-V, --version output the version number
-p, --peppers Add peppers
-P, --pineapple Add pineappe
-b, --bbq Add bbq sauce
-c, --cheese <type> Add the specified type of cheese [marble]
-h, --help output usage information
```
## Coercion
```js
function range(val) {
return val.split('..').map(Number);
}
function list(val) {
return val.split(',');
}
program
.version('0.0.1')
.usage('[options] <file ...>')
.option('-i, --integer <n>', 'An integer argument', parseInt)
.option('-f, --float <n>', 'A float argument', parseFloat)
.option('-r, --range <a>..<b>', 'A range', range)
.option('-l, --list <items>', 'A list', list)
.option('-o, --optional [value]', 'An optional value')
.parse(process.argv);
console.log(' int: %j', program.integer);
console.log(' float: %j', program.float);
console.log(' optional: %j', program.optional);
program.range = program.range || [];
console.log(' range: %j..%j', program.range[0], program.range[1]);
console.log(' list: %j', program.list);
console.log(' args: %j', program.args);
```
## Custom help
You can display arbitrary `-h, --help` information
by listening for "--help". Commander will automatically
exit once you are done so that the remainder of your program
does not execute causing undesired behaviours, for example
in the following executable "stuff" will not output when
`--help` is used.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('../');
function list(val) {
return val.split(',').map(Number);
}
program
.version('0.0.1')
.option('-f, --foo', 'enable some foo')
.option('-b, --bar', 'enable some bar')
.option('-B, --baz', 'enable some baz');
// must be before .parse() since
// node's emit() is immediate
program.on('--help', function(){
console.log(' Examples:');
console.log('');
console.log(' $ custom-help --help');
console.log(' $ custom-help -h');
console.log('');
});
program.parse(process.argv);
console.log('stuff');
```
yielding the following help output:
```
Usage: custom-help [options]
Options:
-h, --help output usage information
-V, --version output the version number
-f, --foo enable some foo
-b, --bar enable some bar
-B, --baz enable some baz
Examples:
$ custom-help --help
$ custom-help -h
```
## .prompt(msg, fn)
Single-line prompt:
```js
program.prompt('name: ', function(name){
console.log('hi %s', name);
});
```
Multi-line prompt:
```js
program.prompt('description:', function(name){
console.log('hi %s', name);
});
```
Coercion:
```js
program.prompt('Age: ', Number, function(age){
console.log('age: %j', age);
});
```
```js
program.prompt('Birthdate: ', Date, function(date){
console.log('date: %s', date);
});
```
## .password(msg[, mask], fn)
Prompt for password without echoing:
```js
program.password('Password: ', function(pass){
console.log('got "%s"', pass);
process.stdin.destroy();
});
```
Prompt for password with mask char "*":
```js
program.password('Password: ', '*', function(pass){
console.log('got "%s"', pass);
process.stdin.destroy();
});
```
## .confirm(msg, fn)
Confirm with the given `msg`:
```js
program.confirm('continue? ', function(ok){
console.log(' got %j', ok);
});
```
## .choose(list, fn)
Let the user choose from a `list`:
```js
var list = ['tobi', 'loki', 'jane', 'manny', 'luna'];
console.log('Choose the coolest pet:');
program.choose(list, function(i){
console.log('you chose %d "%s"', i, list[i]);
});
```
## Links
- [API documentation](http://visionmedia.github.com/commander.js/)
- [ascii tables](https://github.com/LearnBoost/cli-table)
- [progress bars](https://github.com/visionmedia/node-progress)
- [more progress bars](https://github.com/substack/node-multimeter)
- [examples](https://github.com/visionmedia/commander.js/tree/master/examples)
## License
(The MIT License)
Copyright (c) 2011 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.

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,41 @@
{
"name": "commander",
"version": "0.6.1",
"description": "the complete solution for node.js command-line programs",
"keywords": [
"command",
"option",
"parser",
"prompt",
"stdin"
],
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"repository": {
"type": "git",
"url": "git://github.com/visionmedia/commander.js.git"
},
"dependencies": {},
"devDependencies": {
"should": ">= 0.0.1"
},
"scripts": {
"test": "make test"
},
"main": "index",
"engines": {
"node": ">= 0.4.x"
},
"_id": "commander@0.6.1",
"optionalDependencies": {},
"_engineSupported": true,
"_npmVersion": "1.1.24",
"_nodeVersion": "v0.6.19",
"_defaultsLoaded": true,
"dist": {
"shasum": "df1426e3fe77395a59f2efb2cd8f9bdef0411e40"
},
"_from": "commander@0.6.1"
}

View File

@@ -9,3 +9,4 @@ install.sh
support/
test/
.DS_Store
coverage.html

View File

@@ -0,0 +1,5 @@
language: node_js
node_js:
- 0.6
- 0.8
- 0.9

View File

@@ -1,2 +1,4 @@
module.exports = require('./lib/connect');
module.exports = process.env.CONNECT_COV
? require('./lib-cov/connect')
: require('./lib/connect');

View File

@@ -0,0 +1,68 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['cache.js']) {
_$jscoverage['cache.js'] = [];
_$jscoverage['cache.js'][12] = 0;
_$jscoverage['cache.js'][21] = 0;
_$jscoverage['cache.js'][22] = 0;
_$jscoverage['cache.js'][23] = 0;
_$jscoverage['cache.js'][24] = 0;
_$jscoverage['cache.js'][35] = 0;
_$jscoverage['cache.js'][36] = 0;
_$jscoverage['cache.js'][37] = 0;
_$jscoverage['cache.js'][47] = 0;
_$jscoverage['cache.js'][48] = 0;
_$jscoverage['cache.js'][59] = 0;
_$jscoverage['cache.js'][60] = 0;
_$jscoverage['cache.js'][71] = 0;
_$jscoverage['cache.js'][73] = 0;
_$jscoverage['cache.js'][76] = 0;
_$jscoverage['cache.js'][78] = 0;
_$jscoverage['cache.js'][79] = 0;
_$jscoverage['cache.js'][80] = 0;
}
_$jscoverage['cache.js'][12]++;
module.exports = Cache;
_$jscoverage['cache.js'][21]++;
function Cache(limit) {
_$jscoverage['cache.js'][22]++;
this.store = {};
_$jscoverage['cache.js'][23]++;
this.keys = [];
_$jscoverage['cache.js'][24]++;
this.limit = limit;
}
_$jscoverage['cache.js'][35]++;
Cache.prototype.touch = (function (key, i) {
_$jscoverage['cache.js'][36]++;
this.keys.splice(i, 1);
_$jscoverage['cache.js'][37]++;
this.keys.push(key);
});
_$jscoverage['cache.js'][47]++;
Cache.prototype.remove = (function (key) {
_$jscoverage['cache.js'][48]++;
delete this.store[key];
});
_$jscoverage['cache.js'][59]++;
Cache.prototype.get = (function (key) {
_$jscoverage['cache.js'][60]++;
return this.store[key];
});
_$jscoverage['cache.js'][71]++;
Cache.prototype.add = (function (key) {
_$jscoverage['cache.js'][73]++;
var len = this.keys.push(key);
_$jscoverage['cache.js'][76]++;
if (len > this.limit) {
_$jscoverage['cache.js'][76]++;
this.remove(this.keys.shift());
}
_$jscoverage['cache.js'][78]++;
var arr = this.store[key] = [];
_$jscoverage['cache.js'][79]++;
arr.createdAt = new Date();
_$jscoverage['cache.js'][80]++;
return arr;
});
_$jscoverage['cache.js'].source = ["","/*!"," * 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 &gt; this.limit) this.remove(this.keys.shift());",""," var arr = this.store[key] = [];"," arr.createdAt = new Date;"," return arr;","};"];

View File

@@ -0,0 +1,93 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['connect.js']) {
_$jscoverage['connect.js'] = [];
_$jscoverage['connect.js'][13] = 0;
_$jscoverage['connect.js'][22] = 0;
_$jscoverage['connect.js'][26] = 0;
_$jscoverage['connect.js'][32] = 0;
_$jscoverage['connect.js'][38] = 0;
_$jscoverage['connect.js'][44] = 0;
_$jscoverage['connect.js'][50] = 0;
_$jscoverage['connect.js'][56] = 0;
_$jscoverage['connect.js'][65] = 0;
_$jscoverage['connect.js'][66] = 0;
_$jscoverage['connect.js'][67] = 0;
_$jscoverage['connect.js'][68] = 0;
_$jscoverage['connect.js'][69] = 0;
_$jscoverage['connect.js'][70] = 0;
_$jscoverage['connect.js'][71] = 0;
_$jscoverage['connect.js'][72] = 0;
_$jscoverage['connect.js'][74] = 0;
_$jscoverage['connect.js'][75] = 0;
_$jscoverage['connect.js'][81] = 0;
_$jscoverage['connect.js'][87] = 0;
_$jscoverage['connect.js'][88] = 0;
_$jscoverage['connect.js'][89] = 0;
_$jscoverage['connect.js'][90] = 0;
_$jscoverage['connect.js'][91] = 0;
_$jscoverage['connect.js'][92] = 0;
}
_$jscoverage['connect.js'][13]++;
var EventEmitter = require("events").EventEmitter, proto = require("./proto"), utils = require("./utils"), path = require("path"), basename = path.basename, fs = require("fs");
_$jscoverage['connect.js'][22]++;
require("./patch");
_$jscoverage['connect.js'][26]++;
exports = module.exports = createServer;
_$jscoverage['connect.js'][32]++;
exports.version = "2.6.1";
_$jscoverage['connect.js'][38]++;
exports.mime = require("./middleware/static").mime;
_$jscoverage['connect.js'][44]++;
exports.proto = proto;
_$jscoverage['connect.js'][50]++;
exports.middleware = {};
_$jscoverage['connect.js'][56]++;
exports.utils = utils;
_$jscoverage['connect.js'][65]++;
function createServer() {
_$jscoverage['connect.js'][66]++;
function app(req, res) {
_$jscoverage['connect.js'][66]++;
app.handle(req, res);
}
_$jscoverage['connect.js'][67]++;
utils.merge(app, proto);
_$jscoverage['connect.js'][68]++;
utils.merge(app, EventEmitter.prototype);
_$jscoverage['connect.js'][69]++;
app.route = "/";
_$jscoverage['connect.js'][70]++;
app.stack = [];
_$jscoverage['connect.js'][71]++;
for (var i = 0; i < arguments.length; ++i) {
_$jscoverage['connect.js'][72]++;
app.use(arguments[i]);
}
_$jscoverage['connect.js'][74]++;
return app;
}
_$jscoverage['connect.js'][75]++;
;
_$jscoverage['connect.js'][81]++;
createServer.createServer = createServer;
_$jscoverage['connect.js'][87]++;
fs.readdirSync(__dirname + "/middleware").forEach((function (filename) {
_$jscoverage['connect.js'][88]++;
if (! /\.js$/.test(filename)) {
_$jscoverage['connect.js'][88]++;
return;
}
_$jscoverage['connect.js'][89]++;
var name = basename(filename, ".js");
_$jscoverage['connect.js'][90]++;
function load() {
_$jscoverage['connect.js'][90]++;
return require("./middleware/" + name);
}
_$jscoverage['connect.js'][91]++;
exports.middleware.__defineGetter__(name, load);
_$jscoverage['connect.js'][92]++;
exports.__defineGetter__(name, load);
}));
_$jscoverage['connect.js'].source = ["","/*!"," * 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 = '2.6.1';","","/**"," * 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){ app.handle(req, res); }"," utils.merge(app, proto);"," utils.merge(app, EventEmitter.prototype);"," app.route = '/';"," app.stack = [];"," for (var i = 0; i &lt; 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);","});"];

View File

@@ -0,0 +1,6 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['index.js']) {
_$jscoverage['index.js'] = [];
}
_$jscoverage['index.js'].source = ["","/**"," * 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');"," * })"," * .listen(3000);"," * "," * Installation:"," * "," * $ npm install connect"," *"," * Middleware:"," *"," * - [logger](logger.html) request logger with custom format support"," * - [csrf](csrf.html) Cross-site request forgery protection"," * - [compress](compress.html) Gzip compression middleware"," * - [basicAuth](basicAuth.html) basic http authentication"," * - [bodyParser](bodyParser.html) extensible request body parser"," * - [json](json.html) application/json parser"," * - [urlencoded](urlencoded.html) application/x-www-form-urlencoded parser"," * - [multipart](multipart.html) multipart/form-data parser"," * - [timeout](timeout.html) request timeouts"," * - [cookieParser](cookieParser.html) cookie parser"," * - [session](session.html) session management support with bundled MemoryStore"," * - [cookieSession](cookieSession.html) cookie-based session support"," * - [methodOverride](methodOverride.html) faux HTTP method support"," * - [responseTime](responseTime.html) calculates response-time and exposes via X-Response-Time"," * - [staticCache](staticCache.html) memory cache layer for the static() middleware"," * - [static](static.html) streaming static file server supporting `Range` and more"," * - [directory](directory.html) directory listing middleware"," * - [vhost](vhost.html) virtual host sub-domain mapping middleware"," * - [favicon](favicon.html) efficient favicon server (with default icon)"," * - [limit](limit.html) limit the bytesize of request bodies"," * - [query](query.html) automatic querystring parser, populating `req.query`"," * - [errorHandler](errorHandler.html) flexible error handler"," *"," * Links:"," * "," * - list of [3rd-party](https://github.com/senchalabs/connect/wiki) middleware"," * - GitHub [repository](http://github.com/senchalabs/connect)"," * - [test documentation](https://github.com/senchalabs/connect/blob/gh-pages/tests.md)"," * "," */"];

View File

@@ -0,0 +1,128 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/basicAuth.js']) {
_$jscoverage['middleware/basicAuth.js'] = [];
_$jscoverage['middleware/basicAuth.js'][13] = 0;
_$jscoverage['middleware/basicAuth.js'][48] = 0;
_$jscoverage['middleware/basicAuth.js'][49] = 0;
_$jscoverage['middleware/basicAuth.js'][52] = 0;
_$jscoverage['middleware/basicAuth.js'][53] = 0;
_$jscoverage['middleware/basicAuth.js'][54] = 0;
_$jscoverage['middleware/basicAuth.js'][55] = 0;
_$jscoverage['middleware/basicAuth.js'][56] = 0;
_$jscoverage['middleware/basicAuth.js'][57] = 0;
_$jscoverage['middleware/basicAuth.js'][58] = 0;
_$jscoverage['middleware/basicAuth.js'][62] = 0;
_$jscoverage['middleware/basicAuth.js'][64] = 0;
_$jscoverage['middleware/basicAuth.js'][65] = 0;
_$jscoverage['middleware/basicAuth.js'][67] = 0;
_$jscoverage['middleware/basicAuth.js'][68] = 0;
_$jscoverage['middleware/basicAuth.js'][70] = 0;
_$jscoverage['middleware/basicAuth.js'][72] = 0;
_$jscoverage['middleware/basicAuth.js'][74] = 0;
_$jscoverage['middleware/basicAuth.js'][78] = 0;
_$jscoverage['middleware/basicAuth.js'][80] = 0;
_$jscoverage['middleware/basicAuth.js'][84] = 0;
_$jscoverage['middleware/basicAuth.js'][85] = 0;
_$jscoverage['middleware/basicAuth.js'][86] = 0;
_$jscoverage['middleware/basicAuth.js'][87] = 0;
_$jscoverage['middleware/basicAuth.js'][88] = 0;
_$jscoverage['middleware/basicAuth.js'][89] = 0;
_$jscoverage['middleware/basicAuth.js'][90] = 0;
_$jscoverage['middleware/basicAuth.js'][94] = 0;
_$jscoverage['middleware/basicAuth.js'][95] = 0;
_$jscoverage['middleware/basicAuth.js'][96] = 0;
_$jscoverage['middleware/basicAuth.js'][98] = 0;
}
_$jscoverage['middleware/basicAuth.js'][13]++;
var utils = require("../utils"), unauthorized = utils.unauthorized;
_$jscoverage['middleware/basicAuth.js'][48]++;
module.exports = (function basicAuth(callback, realm) {
_$jscoverage['middleware/basicAuth.js'][49]++;
var username, password;
_$jscoverage['middleware/basicAuth.js'][52]++;
if ("string" == typeof callback) {
_$jscoverage['middleware/basicAuth.js'][53]++;
username = callback;
_$jscoverage['middleware/basicAuth.js'][54]++;
password = realm;
_$jscoverage['middleware/basicAuth.js'][55]++;
if ("string" != typeof password) {
_$jscoverage['middleware/basicAuth.js'][55]++;
throw new Error("password argument required");
}
_$jscoverage['middleware/basicAuth.js'][56]++;
realm = arguments[2];
_$jscoverage['middleware/basicAuth.js'][57]++;
callback = (function (user, pass) {
_$jscoverage['middleware/basicAuth.js'][58]++;
return user == username && pass == password;
});
}
_$jscoverage['middleware/basicAuth.js'][62]++;
realm = realm || "Authorization Required";
_$jscoverage['middleware/basicAuth.js'][64]++;
return (function (req, res, next) {
_$jscoverage['middleware/basicAuth.js'][65]++;
var authorization = req.headers.authorization;
_$jscoverage['middleware/basicAuth.js'][67]++;
if (req.user) {
_$jscoverage['middleware/basicAuth.js'][67]++;
return next();
}
_$jscoverage['middleware/basicAuth.js'][68]++;
if (! authorization) {
_$jscoverage['middleware/basicAuth.js'][68]++;
return unauthorized(res, realm);
}
_$jscoverage['middleware/basicAuth.js'][70]++;
var parts = authorization.split(" ");
_$jscoverage['middleware/basicAuth.js'][72]++;
if (parts.length !== 2) {
_$jscoverage['middleware/basicAuth.js'][72]++;
return next(utils.error(400));
}
_$jscoverage['middleware/basicAuth.js'][74]++;
var scheme = parts[0], credentials = new Buffer(parts[1], "base64").toString(), index = credentials.indexOf(":");
_$jscoverage['middleware/basicAuth.js'][78]++;
if ("Basic" != scheme || index < 0) {
_$jscoverage['middleware/basicAuth.js'][78]++;
return next(utils.error(400));
}
_$jscoverage['middleware/basicAuth.js'][80]++;
var user = credentials.slice(0, index), pass = credentials.slice(index + 1);
_$jscoverage['middleware/basicAuth.js'][84]++;
if (callback.length >= 3) {
_$jscoverage['middleware/basicAuth.js'][85]++;
var pause = utils.pause(req);
_$jscoverage['middleware/basicAuth.js'][86]++;
callback(user, pass, (function (err, user) {
_$jscoverage['middleware/basicAuth.js'][87]++;
if (err || ! user) {
_$jscoverage['middleware/basicAuth.js'][87]++;
return unauthorized(res, realm);
}
_$jscoverage['middleware/basicAuth.js'][88]++;
req.user = req.remoteUser = user;
_$jscoverage['middleware/basicAuth.js'][89]++;
next();
_$jscoverage['middleware/basicAuth.js'][90]++;
pause.resume();
}));
}
else {
_$jscoverage['middleware/basicAuth.js'][94]++;
if (callback(user, pass)) {
_$jscoverage['middleware/basicAuth.js'][95]++;
req.user = req.remoteUser = user;
_$jscoverage['middleware/basicAuth.js'][96]++;
next();
}
else {
_$jscoverage['middleware/basicAuth.js'][98]++;
unauthorized(res, realm);
}
}
});
});
_$jscoverage['middleware/basicAuth.js'].source = ["","/*!"," * Connect - basicAuth"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils')"," , unauthorized = utils.unauthorized;","","/**"," * 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 &amp; '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 &amp;&amp; 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(utils.error(400));",""," var scheme = parts[0]"," , credentials = new Buffer(parts[1], 'base64').toString()"," , index = credentials.indexOf(':');",""," if ('Basic' != scheme || index &lt; 0) return next(utils.error(400));"," "," var user = credentials.slice(0, index)"," , pass = credentials.slice(index + 1);",""," // async"," if (callback.length &gt;= 3) {"," var pause = utils.pause(req);"," callback(user, pass, function(err, user){"," if (err || !user) return unauthorized(res, realm);"," req.user = req.remoteUser = user;"," next();"," pause.resume();"," });"," // sync"," } else {"," if (callback(user, pass)) {"," req.user = req.remoteUser = user;"," next();"," } else {"," unauthorized(res, realm);"," }"," }"," }","};",""];

View File

@@ -0,0 +1,43 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/bodyParser.js']) {
_$jscoverage['middleware/bodyParser.js'] = [];
_$jscoverage['middleware/bodyParser.js'][13] = 0;
_$jscoverage['middleware/bodyParser.js'][47] = 0;
_$jscoverage['middleware/bodyParser.js'][48] = 0;
_$jscoverage['middleware/bodyParser.js'][52] = 0;
_$jscoverage['middleware/bodyParser.js'][53] = 0;
_$jscoverage['middleware/bodyParser.js'][54] = 0;
_$jscoverage['middleware/bodyParser.js'][55] = 0;
_$jscoverage['middleware/bodyParser.js'][56] = 0;
_$jscoverage['middleware/bodyParser.js'][57] = 0;
}
_$jscoverage['middleware/bodyParser.js'][13]++;
var multipart = require("./multipart"), urlencoded = require("./urlencoded"), json = require("./json");
_$jscoverage['middleware/bodyParser.js'][47]++;
exports = module.exports = (function bodyParser(options) {
_$jscoverage['middleware/bodyParser.js'][48]++;
var _urlencoded = urlencoded(options), _multipart = multipart(options), _json = json(options);
_$jscoverage['middleware/bodyParser.js'][52]++;
return (function bodyParser(req, res, next) {
_$jscoverage['middleware/bodyParser.js'][53]++;
_json(req, res, (function (err) {
_$jscoverage['middleware/bodyParser.js'][54]++;
if (err) {
_$jscoverage['middleware/bodyParser.js'][54]++;
return next(err);
}
_$jscoverage['middleware/bodyParser.js'][55]++;
_urlencoded(req, res, (function (err) {
_$jscoverage['middleware/bodyParser.js'][56]++;
if (err) {
_$jscoverage['middleware/bodyParser.js'][56]++;
return next(err);
}
_$jscoverage['middleware/bodyParser.js'][57]++;
_multipart(req, res, next);
}));
}));
});
});
_$jscoverage['middleware/bodyParser.js'].source = ["","/*!"," * 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:"," * "," * 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."," *"," * @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);"," });"," });"," }","};"];

View File

@@ -0,0 +1,159 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/compress.js']) {
_$jscoverage['middleware/compress.js'] = [];
_$jscoverage['middleware/compress.js'][12] = 0;
_$jscoverage['middleware/compress.js'][18] = 0;
_$jscoverage['middleware/compress.js'][27] = 0;
_$jscoverage['middleware/compress.js'][28] = 0;
_$jscoverage['middleware/compress.js'][61] = 0;
_$jscoverage['middleware/compress.js'][62] = 0;
_$jscoverage['middleware/compress.js'][63] = 0;
_$jscoverage['middleware/compress.js'][66] = 0;
_$jscoverage['middleware/compress.js'][67] = 0;
_$jscoverage['middleware/compress.js'][74] = 0;
_$jscoverage['middleware/compress.js'][78] = 0;
_$jscoverage['middleware/compress.js'][79] = 0;
_$jscoverage['middleware/compress.js'][80] = 0;
_$jscoverage['middleware/compress.js'][85] = 0;
_$jscoverage['middleware/compress.js'][86] = 0;
_$jscoverage['middleware/compress.js'][87] = 0;
_$jscoverage['middleware/compress.js'][92] = 0;
_$jscoverage['middleware/compress.js'][93] = 0;
_$jscoverage['middleware/compress.js'][96] = 0;
_$jscoverage['middleware/compress.js'][99] = 0;
_$jscoverage['middleware/compress.js'][102] = 0;
_$jscoverage['middleware/compress.js'][105] = 0;
_$jscoverage['middleware/compress.js'][108] = 0;
_$jscoverage['middleware/compress.js'][111] = 0;
_$jscoverage['middleware/compress.js'][112] = 0;
_$jscoverage['middleware/compress.js'][113] = 0;
_$jscoverage['middleware/compress.js'][114] = 0;
_$jscoverage['middleware/compress.js'][115] = 0;
_$jscoverage['middleware/compress.js'][121] = 0;
_$jscoverage['middleware/compress.js'][124] = 0;
_$jscoverage['middleware/compress.js'][127] = 0;
_$jscoverage['middleware/compress.js'][128] = 0;
_$jscoverage['middleware/compress.js'][132] = 0;
_$jscoverage['middleware/compress.js'][133] = 0;
_$jscoverage['middleware/compress.js'][136] = 0;
_$jscoverage['middleware/compress.js'][137] = 0;
_$jscoverage['middleware/compress.js'][140] = 0;
_$jscoverage['middleware/compress.js'][141] = 0;
_$jscoverage['middleware/compress.js'][145] = 0;
}
_$jscoverage['middleware/compress.js'][12]++;
var zlib = require("zlib");
_$jscoverage['middleware/compress.js'][18]++;
exports.methods = {gzip: zlib.createGzip, deflate: zlib.createDeflate};
_$jscoverage['middleware/compress.js'][27]++;
exports.filter = (function (req, res) {
_$jscoverage['middleware/compress.js'][28]++;
return /json|text|javascript/.test(res.getHeader("Content-Type"));
});
_$jscoverage['middleware/compress.js'][61]++;
module.exports = (function compress(options) {
_$jscoverage['middleware/compress.js'][62]++;
options = options || {};
_$jscoverage['middleware/compress.js'][63]++;
var names = Object.keys(exports.methods), filter = options.filter || exports.filter;
_$jscoverage['middleware/compress.js'][66]++;
return (function (req, res, next) {
_$jscoverage['middleware/compress.js'][67]++;
var accept = req.headers["accept-encoding"], write = res.write, end = res.end, stream, method;
_$jscoverage['middleware/compress.js'][74]++;
res.setHeader("Vary", "Accept-Encoding");
_$jscoverage['middleware/compress.js'][78]++;
res.write = (function (chunk, encoding) {
_$jscoverage['middleware/compress.js'][79]++;
if (! this.headerSent) {
_$jscoverage['middleware/compress.js'][79]++;
this._implicitHeader();
}
_$jscoverage['middleware/compress.js'][80]++;
return stream? stream.write(new Buffer(chunk, encoding)): write.call(res, chunk, encoding);
});
_$jscoverage['middleware/compress.js'][85]++;
res.end = (function (chunk, encoding) {
_$jscoverage['middleware/compress.js'][86]++;
if (chunk) {
_$jscoverage['middleware/compress.js'][86]++;
this.write(chunk, encoding);
}
_$jscoverage['middleware/compress.js'][87]++;
return stream? stream.end(): end.call(res);
});
_$jscoverage['middleware/compress.js'][92]++;
res.on("header", (function () {
_$jscoverage['middleware/compress.js'][93]++;
var encoding = res.getHeader("Content-Encoding") || "identity";
_$jscoverage['middleware/compress.js'][96]++;
if ("identity" != encoding) {
_$jscoverage['middleware/compress.js'][96]++;
return;
}
_$jscoverage['middleware/compress.js'][99]++;
if (! filter(req, res)) {
_$jscoverage['middleware/compress.js'][99]++;
return;
}
_$jscoverage['middleware/compress.js'][102]++;
if (! accept) {
_$jscoverage['middleware/compress.js'][102]++;
return;
}
_$jscoverage['middleware/compress.js'][105]++;
if ("HEAD" == req.method) {
_$jscoverage['middleware/compress.js'][105]++;
return;
}
_$jscoverage['middleware/compress.js'][108]++;
if ("*" == accept.trim()) {
_$jscoverage['middleware/compress.js'][108]++;
method = "gzip";
}
_$jscoverage['middleware/compress.js'][111]++;
if (! method) {
_$jscoverage['middleware/compress.js'][112]++;
for (var i = 0, len = names.length; i < len; ++i) {
_$jscoverage['middleware/compress.js'][113]++;
if (~ accept.indexOf(names[i])) {
_$jscoverage['middleware/compress.js'][114]++;
method = names[i];
_$jscoverage['middleware/compress.js'][115]++;
break;
}
}
}
_$jscoverage['middleware/compress.js'][121]++;
if (! method) {
_$jscoverage['middleware/compress.js'][121]++;
return;
}
_$jscoverage['middleware/compress.js'][124]++;
stream = exports.methods[method](options);
_$jscoverage['middleware/compress.js'][127]++;
res.setHeader("Content-Encoding", method);
_$jscoverage['middleware/compress.js'][128]++;
res.removeHeader("Content-Length");
_$jscoverage['middleware/compress.js'][132]++;
stream.on("data", (function (chunk) {
_$jscoverage['middleware/compress.js'][133]++;
write.call(res, chunk);
}));
_$jscoverage['middleware/compress.js'][136]++;
stream.on("end", (function () {
_$jscoverage['middleware/compress.js'][137]++;
end.call(res);
}));
_$jscoverage['middleware/compress.js'][140]++;
stream.on("drain", (function () {
_$jscoverage['middleware/compress.js'][141]++;
res.emit("drain");
}));
}));
_$jscoverage['middleware/compress.js'][145]++;
next();
});
});
_$jscoverage['middleware/compress.js'].source = ["/*!"," * Connect - compress"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var zlib = require('zlib');","","/**"," * Supported content-encoding methods."," */","","exports.methods = {"," gzip: zlib.createGzip"," , deflate: zlib.createDeflate","};","","/**"," * Default filter function."," */","","exports.filter = function(req, res){"," return /json|text|javascript/.test(res.getHeader('Content-Type'));","};","","/**"," * Compress:"," *"," * Compress response data with gzip/deflate."," *"," * Filter:"," *"," * A `filter` callback function may be passed to"," * replace the default logic of:"," *"," * exports.filter = function(req, res){"," * return /json|text|javascript/.test(res.getHeader('Content-Type'));"," * };"," *"," * Options:"," *"," * All remaining options are passed to the gzip/deflate"," * creation functions. Consult node's docs for additional details."," *"," * - `chunkSize` (default: 16*1024)"," * - `windowBits`"," * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression"," * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more"," * - `strategy`: compression strategy"," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","module.exports = function compress(options) {"," options = options || {};"," var names = Object.keys(exports.methods)"," , filter = options.filter || exports.filter;",""," return function(req, res, next){"," var accept = req.headers['accept-encoding']"," , write = res.write"," , end = res.end"," , stream"," , method;",""," // vary"," res.setHeader('Vary', 'Accept-Encoding');",""," // proxy",""," res.write = function(chunk, encoding){"," if (!this.headerSent) this._implicitHeader();"," return stream"," ? stream.write(new Buffer(chunk, encoding))"," : write.call(res, chunk, encoding);"," };",""," res.end = function(chunk, encoding){"," if (chunk) this.write(chunk, encoding);"," return stream"," ? stream.end()"," : end.call(res);"," };",""," res.on('header', function(){"," var encoding = res.getHeader('Content-Encoding') || 'identity';",""," // already encoded"," if ('identity' != encoding) return; ",""," // default request filter"," if (!filter(req, res)) return;",""," // SHOULD use identity"," if (!accept) return;",""," // head"," if ('HEAD' == req.method) return;",""," // default to gzip"," if ('*' == accept.trim()) method = 'gzip';",""," // compression method"," if (!method) {"," for (var i = 0, len = names.length; i &lt; len; ++i) {"," if (~accept.indexOf(names[i])) {"," method = names[i];"," break;"," }"," }"," }",""," // compression method"," if (!method) return;",""," // compression stream"," stream = exports.methods[method](options);",""," // header fields"," res.setHeader('Content-Encoding', method);"," res.removeHeader('Content-Length');",""," // compression",""," stream.on('data', function(chunk){"," write.call(res, chunk);"," });",""," stream.on('end', function(){"," end.call(res);"," });",""," stream.on('drain', function() {"," res.emit('drain');"," });"," });",""," next();"," };","};"];

View File

@@ -0,0 +1,70 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/cookieParser.js']) {
_$jscoverage['middleware/cookieParser.js'] = [];
_$jscoverage['middleware/cookieParser.js'][13] = 0;
_$jscoverage['middleware/cookieParser.js'][38] = 0;
_$jscoverage['middleware/cookieParser.js'][39] = 0;
_$jscoverage['middleware/cookieParser.js'][40] = 0;
_$jscoverage['middleware/cookieParser.js'][41] = 0;
_$jscoverage['middleware/cookieParser.js'][43] = 0;
_$jscoverage['middleware/cookieParser.js'][44] = 0;
_$jscoverage['middleware/cookieParser.js'][45] = 0;
_$jscoverage['middleware/cookieParser.js'][47] = 0;
_$jscoverage['middleware/cookieParser.js'][48] = 0;
_$jscoverage['middleware/cookieParser.js'][49] = 0;
_$jscoverage['middleware/cookieParser.js'][50] = 0;
_$jscoverage['middleware/cookieParser.js'][51] = 0;
_$jscoverage['middleware/cookieParser.js'][52] = 0;
_$jscoverage['middleware/cookieParser.js'][54] = 0;
_$jscoverage['middleware/cookieParser.js'][56] = 0;
_$jscoverage['middleware/cookieParser.js'][57] = 0;
_$jscoverage['middleware/cookieParser.js'][60] = 0;
}
_$jscoverage['middleware/cookieParser.js'][13]++;
var utils = require("./../utils"), cookie = require("cookie");
_$jscoverage['middleware/cookieParser.js'][38]++;
module.exports = (function cookieParser(secret) {
_$jscoverage['middleware/cookieParser.js'][39]++;
return (function cookieParser(req, res, next) {
_$jscoverage['middleware/cookieParser.js'][40]++;
if (req.cookies) {
_$jscoverage['middleware/cookieParser.js'][40]++;
return next();
}
_$jscoverage['middleware/cookieParser.js'][41]++;
var cookies = req.headers.cookie;
_$jscoverage['middleware/cookieParser.js'][43]++;
req.secret = secret;
_$jscoverage['middleware/cookieParser.js'][44]++;
req.cookies = {};
_$jscoverage['middleware/cookieParser.js'][45]++;
req.signedCookies = {};
_$jscoverage['middleware/cookieParser.js'][47]++;
if (cookies) {
_$jscoverage['middleware/cookieParser.js'][48]++;
try {
_$jscoverage['middleware/cookieParser.js'][49]++;
req.cookies = cookie.parse(cookies);
_$jscoverage['middleware/cookieParser.js'][50]++;
if (secret) {
_$jscoverage['middleware/cookieParser.js'][51]++;
req.signedCookies = utils.parseSignedCookies(req.cookies, secret);
_$jscoverage['middleware/cookieParser.js'][52]++;
req.signedCookies = utils.parseJSONCookies(req.signedCookies);
}
_$jscoverage['middleware/cookieParser.js'][54]++;
req.cookies = utils.parseJSONCookies(req.cookies);
}
catch (err) {
_$jscoverage['middleware/cookieParser.js'][56]++;
err.status = 400;
_$jscoverage['middleware/cookieParser.js'][57]++;
return next(err);
}
}
_$jscoverage['middleware/cookieParser.js'][60]++;
next();
});
});
_$jscoverage['middleware/cookieParser.js'].source = ["","/*!"," * Connect - cookieParser"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('./../utils')"," , cookie = require('cookie');","","/**"," * Cookie parser:"," *"," * Parse _Cookie_ header and populate `req.cookies`"," * with an object keyed by the cookie names. Optionally"," * you may enabled signed cookie support by passing"," * a `secret` string, which assigns `req.secret` so"," * it may be used by other middleware."," *"," * Examples:"," *"," * connect()"," * .use(connect.cookieParser('optional secret string'))"," * .use(function(req, res, next){"," * res.end(JSON.stringify(req.cookies));"," * })"," *"," * @param {String} secret"," * @return {Function}"," * @api public"," */","","module.exports = function cookieParser(secret){"," return function cookieParser(req, res, next) {"," if (req.cookies) return next();"," var cookies = req.headers.cookie;",""," req.secret = secret;"," req.cookies = {};"," req.signedCookies = {};",""," if (cookies) {"," try {"," req.cookies = cookie.parse(cookies);"," if (secret) {"," req.signedCookies = utils.parseSignedCookies(req.cookies, secret);"," req.signedCookies = utils.parseJSONCookies(req.signedCookies);"," }"," req.cookies = utils.parseJSONCookies(req.cookies);"," } catch (err) {"," err.status = 400;"," return next(err);"," }"," }"," next();"," };","};"];

View File

@@ -0,0 +1,132 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/cookieSession.js']) {
_$jscoverage['middleware/cookieSession.js'] = [];
_$jscoverage['middleware/cookieSession.js'][12] = 0;
_$jscoverage['middleware/cookieSession.js'][46] = 0;
_$jscoverage['middleware/cookieSession.js'][48] = 0;
_$jscoverage['middleware/cookieSession.js'][49] = 0;
_$jscoverage['middleware/cookieSession.js'][52] = 0;
_$jscoverage['middleware/cookieSession.js'][55] = 0;
_$jscoverage['middleware/cookieSession.js'][56] = 0;
_$jscoverage['middleware/cookieSession.js'][59] = 0;
_$jscoverage['middleware/cookieSession.js'][60] = 0;
_$jscoverage['middleware/cookieSession.js'][63] = 0;
_$jscoverage['middleware/cookieSession.js'][66] = 0;
_$jscoverage['middleware/cookieSession.js'][67] = 0;
_$jscoverage['middleware/cookieSession.js'][70] = 0;
_$jscoverage['middleware/cookieSession.js'][71] = 0;
_$jscoverage['middleware/cookieSession.js'][72] = 0;
_$jscoverage['middleware/cookieSession.js'][73] = 0;
_$jscoverage['middleware/cookieSession.js'][74] = 0;
_$jscoverage['middleware/cookieSession.js'][75] = 0;
_$jscoverage['middleware/cookieSession.js'][80] = 0;
_$jscoverage['middleware/cookieSession.js'][82] = 0;
_$jscoverage['middleware/cookieSession.js'][83] = 0;
_$jscoverage['middleware/cookieSession.js'][84] = 0;
_$jscoverage['middleware/cookieSession.js'][85] = 0;
_$jscoverage['middleware/cookieSession.js'][86] = 0;
_$jscoverage['middleware/cookieSession.js'][89] = 0;
_$jscoverage['middleware/cookieSession.js'][92] = 0;
_$jscoverage['middleware/cookieSession.js'][97] = 0;
_$jscoverage['middleware/cookieSession.js'][100] = 0;
_$jscoverage['middleware/cookieSession.js'][101] = 0;
_$jscoverage['middleware/cookieSession.js'][104] = 0;
_$jscoverage['middleware/cookieSession.js'][107] = 0;
_$jscoverage['middleware/cookieSession.js'][108] = 0;
_$jscoverage['middleware/cookieSession.js'][109] = 0;
_$jscoverage['middleware/cookieSession.js'][110] = 0;
_$jscoverage['middleware/cookieSession.js'][113] = 0;
}
_$jscoverage['middleware/cookieSession.js'][12]++;
var utils = require("./../utils"), Cookie = require("./session/cookie"), debug = require("debug")("connect:cookieSession"), signature = require("cookie-signature"), crc16 = require("crc").crc16;
_$jscoverage['middleware/cookieSession.js'][46]++;
module.exports = (function cookieSession(options) {
_$jscoverage['middleware/cookieSession.js'][48]++;
options = options || {};
_$jscoverage['middleware/cookieSession.js'][49]++;
var key = options.key || "connect.sess", trustProxy = options.proxy;
_$jscoverage['middleware/cookieSession.js'][52]++;
return (function cookieSession(req, res, next) {
_$jscoverage['middleware/cookieSession.js'][55]++;
var secret = options.secret || req.secret;
_$jscoverage['middleware/cookieSession.js'][56]++;
if (! secret) {
_$jscoverage['middleware/cookieSession.js'][56]++;
throw new Error("`secret` option required for cookie sessions");
}
_$jscoverage['middleware/cookieSession.js'][59]++;
req.session = {};
_$jscoverage['middleware/cookieSession.js'][60]++;
var cookie = req.session.cookie = new Cookie(options.cookie);
_$jscoverage['middleware/cookieSession.js'][63]++;
if (0 != req.originalUrl.indexOf(cookie.path)) {
_$jscoverage['middleware/cookieSession.js'][63]++;
return next();
}
_$jscoverage['middleware/cookieSession.js'][66]++;
if (! options.secret && req.secret) {
_$jscoverage['middleware/cookieSession.js'][67]++;
req.session = req.signedCookies[key] || {};
}
else {
_$jscoverage['middleware/cookieSession.js'][70]++;
var rawCookie = req.cookies[key];
_$jscoverage['middleware/cookieSession.js'][71]++;
if (rawCookie) {
_$jscoverage['middleware/cookieSession.js'][72]++;
var unsigned = utils.parseSignedCookie(rawCookie, secret);
_$jscoverage['middleware/cookieSession.js'][73]++;
if (unsigned) {
_$jscoverage['middleware/cookieSession.js'][74]++;
var originalHash = crc16(unsigned);
_$jscoverage['middleware/cookieSession.js'][75]++;
req.session = utils.parseJSONCookie(unsigned) || {};
}
}
}
_$jscoverage['middleware/cookieSession.js'][80]++;
res.on("header", (function () {
_$jscoverage['middleware/cookieSession.js'][82]++;
if (! req.session) {
_$jscoverage['middleware/cookieSession.js'][83]++;
debug("clear session");
_$jscoverage['middleware/cookieSession.js'][84]++;
cookie.expires = new Date(0);
_$jscoverage['middleware/cookieSession.js'][85]++;
res.setHeader("Set-Cookie", cookie.serialize(key, ""));
_$jscoverage['middleware/cookieSession.js'][86]++;
return;
}
_$jscoverage['middleware/cookieSession.js'][89]++;
delete req.session.cookie;
_$jscoverage['middleware/cookieSession.js'][92]++;
var proto = (req.headers["x-forwarded-proto"] || "").toLowerCase(), tls = req.connection.encrypted || (trustProxy && "https" == proto), secured = cookie.secure && tls;
_$jscoverage['middleware/cookieSession.js'][97]++;
if (cookie.secure && ! secured) {
_$jscoverage['middleware/cookieSession.js'][97]++;
return debug("not secured");
}
_$jscoverage['middleware/cookieSession.js'][100]++;
debug("serializing %j", req.session);
_$jscoverage['middleware/cookieSession.js'][101]++;
var val = "j:" + JSON.stringify(req.session);
_$jscoverage['middleware/cookieSession.js'][104]++;
if (originalHash == crc16(val)) {
_$jscoverage['middleware/cookieSession.js'][104]++;
return debug("unmodified session");
}
_$jscoverage['middleware/cookieSession.js'][107]++;
val = "s:" + signature.sign(val, secret);
_$jscoverage['middleware/cookieSession.js'][108]++;
val = cookie.serialize(key, val);
_$jscoverage['middleware/cookieSession.js'][109]++;
debug("set-cookie %j", cookie);
_$jscoverage['middleware/cookieSession.js'][110]++;
res.setHeader("Set-Cookie", val);
}));
_$jscoverage['middleware/cookieSession.js'][113]++;
next();
});
});
_$jscoverage['middleware/cookieSession.js'].source = ["","/*!"," * Connect - cookieSession"," * Copyright(c) 2011 Sencha Inc."," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('./../utils')"," , Cookie = require('./session/cookie')"," , debug = require('debug')('connect:cookieSession')"," , signature = require('cookie-signature')"," , crc16 = require('crc').crc16;","","/**"," * 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;"," *"," * @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"," if (0 != req.originalUrl.indexOf(cookie.path)) return next();",""," // cookieParser secret"," if (!options.secret &amp;&amp; req.secret) {"," req.session = req.signedCookies[key] || {};"," } else {"," // TODO: refactor"," var rawCookie = req.cookies[key];"," if (rawCookie) {"," var unsigned = utils.parseSignedCookie(rawCookie, secret);"," if (unsigned) {"," var originalHash = crc16(unsigned);"," req.session = utils.parseJSONCookie(unsigned) || {};"," }"," }"," }",""," res.on('header', 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 &amp;&amp; 'https' == proto)"," , secured = cookie.secure &amp;&amp; tls;",""," // only send secure cookies via https"," if (cookie.secure &amp;&amp; !secured) return debug('not secured');",""," // serialize"," debug('serializing %j', req.session);"," var val = 'j:' + JSON.stringify(req.session);",""," // compare hashes, no need to set-cookie if unchanged"," if (originalHash == crc16(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();"," };","};"];

View File

@@ -0,0 +1,51 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/csrf.js']) {
_$jscoverage['middleware/csrf.js'] = [];
_$jscoverage['middleware/csrf.js'][11] = 0;
_$jscoverage['middleware/csrf.js'][39] = 0;
_$jscoverage['middleware/csrf.js'][40] = 0;
_$jscoverage['middleware/csrf.js'][41] = 0;
_$jscoverage['middleware/csrf.js'][43] = 0;
_$jscoverage['middleware/csrf.js'][45] = 0;
_$jscoverage['middleware/csrf.js'][48] = 0;
_$jscoverage['middleware/csrf.js'][51] = 0;
_$jscoverage['middleware/csrf.js'][54] = 0;
_$jscoverage['middleware/csrf.js'][56] = 0;
_$jscoverage['middleware/csrf.js'][69] = 0;
_$jscoverage['middleware/csrf.js'][70] = 0;
}
_$jscoverage['middleware/csrf.js'][11]++;
var utils = require("../utils");
_$jscoverage['middleware/csrf.js'][39]++;
module.exports = (function csrf(options) {
_$jscoverage['middleware/csrf.js'][40]++;
options = options || {};
_$jscoverage['middleware/csrf.js'][41]++;
var value = options.value || defaultValue;
_$jscoverage['middleware/csrf.js'][43]++;
return (function (req, res, next) {
_$jscoverage['middleware/csrf.js'][45]++;
var token = req.session._csrf || (req.session._csrf = utils.uid(24));
_$jscoverage['middleware/csrf.js'][48]++;
if ("GET" == req.method || "HEAD" == req.method || "OPTIONS" == req.method) {
_$jscoverage['middleware/csrf.js'][48]++;
return next();
}
_$jscoverage['middleware/csrf.js'][51]++;
var val = value(req);
_$jscoverage['middleware/csrf.js'][54]++;
if (val != token) {
_$jscoverage['middleware/csrf.js'][54]++;
return next(utils.error(403));
}
_$jscoverage['middleware/csrf.js'][56]++;
next();
});
});
_$jscoverage['middleware/csrf.js'][69]++;
function defaultValue(req) {
_$jscoverage['middleware/csrf.js'][70]++;
return (req.body && req.body._csrf) || (req.query && req.query._csrf) || req.headers["x-csrf-token"];
}
_$jscoverage['middleware/csrf.js'].source = ["/*!"," * Connect - csrf"," * Copyright(c) 2011 Sencha Inc."," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils');","","/**"," * Anti CSRF:"," *"," * CRSF protection middleware."," *"," * By default this middleware generates a token named \"_csrf\""," * which should be added to requests which mutate"," * state, within a hidden form field, query-string etc. This"," * token is validated against the visitor's `req.session._csrf`"," * property."," *"," * The default `value` function checks `req.body` generated"," * by the `bodyParser()` middleware, `req.query` generated"," * by `query()`, and the \"X-CSRF-Token\" header field."," *"," * This middleware requires session support, thus should be added"," * somewhere _below_ `session()` and `cookieParser()`."," *"," * Options:"," *"," * - `value` a function accepting the request, returning the token "," *"," * @param {Object} options"," * @api public"," */","","module.exports = function csrf(options) {"," options = options || {};"," var value = options.value || defaultValue;",""," return function(req, res, next){"," // generate CSRF token"," var token = req.session._csrf || (req.session._csrf = utils.uid(24));",""," // ignore these methods"," if ('GET' == req.method || 'HEAD' == req.method || 'OPTIONS' == req.method) return next();",""," // determine value"," var val = value(req);",""," // check"," if (val != token) return next(utils.error(403));"," "," next();"," }","};","","/**"," * Default value function, checking the `req.body`"," * and `req.query` for the CSRF token."," *"," * @param {IncomingMessage} req"," * @return {String}"," * @api private"," */","","function defaultValue(req) {"," return (req.body &amp;&amp; req.body._csrf)"," || (req.query &amp;&amp; req.query._csrf)"," || (req.headers['x-csrf-token']);","}"];

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,104 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/errorHandler.js']) {
_$jscoverage['middleware/errorHandler.js'] = [];
_$jscoverage['middleware/errorHandler.js'][12] = 0;
_$jscoverage['middleware/errorHandler.js'][17] = 0;
_$jscoverage['middleware/errorHandler.js'][44] = 0;
_$jscoverage['middleware/errorHandler.js'][45] = 0;
_$jscoverage['middleware/errorHandler.js'][46] = 0;
_$jscoverage['middleware/errorHandler.js'][47] = 0;
_$jscoverage['middleware/errorHandler.js'][48] = 0;
_$jscoverage['middleware/errorHandler.js'][49] = 0;
_$jscoverage['middleware/errorHandler.js'][51] = 0;
_$jscoverage['middleware/errorHandler.js'][52] = 0;
_$jscoverage['middleware/errorHandler.js'][53] = 0;
_$jscoverage['middleware/errorHandler.js'][54] = 0;
_$jscoverage['middleware/errorHandler.js'][56] = 0;
_$jscoverage['middleware/errorHandler.js'][57] = 0;
_$jscoverage['middleware/errorHandler.js'][63] = 0;
_$jscoverage['middleware/errorHandler.js'][64] = 0;
_$jscoverage['middleware/errorHandler.js'][68] = 0;
_$jscoverage['middleware/errorHandler.js'][69] = 0;
_$jscoverage['middleware/errorHandler.js'][70] = 0;
_$jscoverage['middleware/errorHandler.js'][71] = 0;
_$jscoverage['middleware/errorHandler.js'][72] = 0;
_$jscoverage['middleware/errorHandler.js'][73] = 0;
_$jscoverage['middleware/errorHandler.js'][76] = 0;
_$jscoverage['middleware/errorHandler.js'][77] = 0;
_$jscoverage['middleware/errorHandler.js'][86] = 0;
}
_$jscoverage['middleware/errorHandler.js'][12]++;
var utils = require("../utils"), fs = require("fs");
_$jscoverage['middleware/errorHandler.js'][17]++;
var env = process.env.NODE_ENV || "development";
_$jscoverage['middleware/errorHandler.js'][44]++;
exports = module.exports = (function errorHandler() {
_$jscoverage['middleware/errorHandler.js'][45]++;
return (function errorHandler(err, req, res, next) {
_$jscoverage['middleware/errorHandler.js'][46]++;
if (err.status) {
_$jscoverage['middleware/errorHandler.js'][46]++;
res.statusCode = err.status;
}
_$jscoverage['middleware/errorHandler.js'][47]++;
if (res.statusCode < 400) {
_$jscoverage['middleware/errorHandler.js'][47]++;
res.statusCode = 500;
}
_$jscoverage['middleware/errorHandler.js'][48]++;
if ("test" != env) {
_$jscoverage['middleware/errorHandler.js'][48]++;
console.error(err.stack);
}
_$jscoverage['middleware/errorHandler.js'][49]++;
var accept = req.headers.accept || "";
_$jscoverage['middleware/errorHandler.js'][51]++;
if (~ accept.indexOf("html")) {
_$jscoverage['middleware/errorHandler.js'][52]++;
fs.readFile(__dirname + "/../public/style.css", "utf8", (function (e, style) {
_$jscoverage['middleware/errorHandler.js'][53]++;
fs.readFile(__dirname + "/../public/error.html", "utf8", (function (e, html) {
_$jscoverage['middleware/errorHandler.js'][54]++;
var stack = (err.stack || "").split("\n").slice(1).map((function (v) {
_$jscoverage['middleware/errorHandler.js'][56]++;
return "<li>" + v + "</li>";
})).join("");
_$jscoverage['middleware/errorHandler.js'][57]++;
html = html.replace("{style}", style).replace("{stack}", stack).replace("{title}", exports.title).replace("{statusCode}", res.statusCode).replace(/\{error\}/g, utils.escape(err.toString()));
_$jscoverage['middleware/errorHandler.js'][63]++;
res.setHeader("Content-Type", "text/html; charset=utf-8");
_$jscoverage['middleware/errorHandler.js'][64]++;
res.end(html);
}));
}));
}
else {
_$jscoverage['middleware/errorHandler.js'][68]++;
if (~ accept.indexOf("json")) {
_$jscoverage['middleware/errorHandler.js'][69]++;
var error = {message: err.message, stack: err.stack};
_$jscoverage['middleware/errorHandler.js'][70]++;
for (var prop in err) {
_$jscoverage['middleware/errorHandler.js'][70]++;
error[prop] = err[prop];
}
_$jscoverage['middleware/errorHandler.js'][71]++;
var json = JSON.stringify({error: error});
_$jscoverage['middleware/errorHandler.js'][72]++;
res.setHeader("Content-Type", "application/json");
_$jscoverage['middleware/errorHandler.js'][73]++;
res.end(json);
}
else {
_$jscoverage['middleware/errorHandler.js'][76]++;
res.writeHead(res.statusCode, {"Content-Type": "text/plain"});
_$jscoverage['middleware/errorHandler.js'][77]++;
res.end(err.stack);
}
}
});
});
_$jscoverage['middleware/errorHandler.js'][86]++;
exports.title = "Connect";
_$jscoverage['middleware/errorHandler.js'].source = ["/*!"," * Connect - errorHandler"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils')"," , fs = require('fs');","","// environment","","var env = process.env.NODE_ENV || 'development';","","/**"," * Error handler:"," *"," * Development error handler, providing stack traces"," * and error message responses for requests accepting text, html,"," * or json."," *"," * Text:"," *"," * By default, and when _text/plain_ is accepted a simple stack trace"," * or error message will be returned."," *"," * JSON:"," *"," * When _application/json_ is accepted, connect will respond with"," * an object in the form of `{ \"error\": error }`."," *"," * HTML:"," *"," * When accepted connect will output a nice html stack trace."," *"," * @return {Function}"," * @api public"," */","","exports = module.exports = function errorHandler(){"," return function errorHandler(err, req, res, next){"," if (err.status) res.statusCode = err.status;"," if (res.statusCode &lt; 400) res.statusCode = 500;"," if ('test' != env) console.error(err.stack);"," var accept = req.headers.accept || '';"," // html"," if (~accept.indexOf('html')) {"," fs.readFile(__dirname + '/../public/style.css', 'utf8', function(e, style){"," fs.readFile(__dirname + '/../public/error.html', 'utf8', function(e, html){"," var stack = (err.stack || '')"," .split('\\n').slice(1)"," .map(function(v){ return '&lt;li&gt;' + v + '&lt;/li&gt;'; }).join('');"," html = html"," .replace('{style}', style)"," .replace('{stack}', stack)"," .replace('{title}', exports.title)"," .replace('{statusCode}', res.statusCode)"," .replace(/\\{error\\}/g, utils.escape(err.toString()));"," res.setHeader('Content-Type', 'text/html; charset=utf-8');"," res.end(html);"," });"," });"," // json"," } else if (~accept.indexOf('json')) {"," var error = { message: err.message, stack: err.stack };"," for (var prop in err) error[prop] = err[prop];"," var json = JSON.stringify({ error: error });"," res.setHeader('Content-Type', 'application/json');"," res.end(json);"," // plain text"," } else {"," res.writeHead(res.statusCode, { 'Content-Type': 'text/plain' });"," res.end(err.stack);"," }"," };","};","","/**"," * Template title, framework authors may override this value."," */","","exports.title = 'Connect';"];

View File

@@ -0,0 +1,60 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/favicon.js']) {
_$jscoverage['middleware/favicon.js'] = [];
_$jscoverage['middleware/favicon.js'][13] = 0;
_$jscoverage['middleware/favicon.js'][50] = 0;
_$jscoverage['middleware/favicon.js'][51] = 0;
_$jscoverage['middleware/favicon.js'][56] = 0;
_$jscoverage['middleware/favicon.js'][57] = 0;
_$jscoverage['middleware/favicon.js'][58] = 0;
_$jscoverage['middleware/favicon.js'][59] = 0;
_$jscoverage['middleware/favicon.js'][60] = 0;
_$jscoverage['middleware/favicon.js'][62] = 0;
_$jscoverage['middleware/favicon.js'][63] = 0;
_$jscoverage['middleware/favicon.js'][64] = 0;
_$jscoverage['middleware/favicon.js'][73] = 0;
_$jscoverage['middleware/favicon.js'][74] = 0;
_$jscoverage['middleware/favicon.js'][78] = 0;
}
_$jscoverage['middleware/favicon.js'][13]++;
var fs = require("fs"), utils = require("../utils");
_$jscoverage['middleware/favicon.js'][50]++;
module.exports = (function favicon(path, options) {
_$jscoverage['middleware/favicon.js'][51]++;
var options = options || {}, path = path || __dirname + "/../public/favicon.ico", maxAge = options.maxAge || 86400000, icon;
_$jscoverage['middleware/favicon.js'][56]++;
return (function favicon(req, res, next) {
_$jscoverage['middleware/favicon.js'][57]++;
if ("/favicon.ico" == req.url) {
_$jscoverage['middleware/favicon.js'][58]++;
if (icon) {
_$jscoverage['middleware/favicon.js'][59]++;
res.writeHead(200, icon.headers);
_$jscoverage['middleware/favicon.js'][60]++;
res.end(icon.body);
}
else {
_$jscoverage['middleware/favicon.js'][62]++;
fs.readFile(path, (function (err, buf) {
_$jscoverage['middleware/favicon.js'][63]++;
if (err) {
_$jscoverage['middleware/favicon.js'][63]++;
return next(err);
}
_$jscoverage['middleware/favicon.js'][64]++;
icon = {headers: {"Content-Type": "image/x-icon", "Content-Length": buf.length, "ETag": "\"" + utils.md5(buf) + "\"", "Cache-Control": "public, max-age=" + (maxAge / 1000)}, body: buf};
_$jscoverage['middleware/favicon.js'][73]++;
res.writeHead(200, icon.headers);
_$jscoverage['middleware/favicon.js'][74]++;
res.end(icon.body);
}));
}
}
else {
_$jscoverage['middleware/favicon.js'][78]++;
next();
}
});
});
_$jscoverage['middleware/favicon.js'].source = ["","/*!"," * Connect - favicon"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var fs = require('fs')"," , utils = require('../utils');","","/**"," * Favicon:"," *"," * By default serves the connect favicon, or the favicon"," * located by the given `path`."," *"," * Options:"," *"," * - `maxAge` cache-control max-age directive, defaulting to 1 day"," *"," * Examples:"," *"," * Serve default favicon:"," *"," * connect()"," * .use(connect.favicon())"," *"," * Serve favicon before logging for brevity:"," *"," * connect()"," * .use(connect.favicon())"," * .use(connect.logger('dev'))"," *"," * Serve custom favicon:"," *"," * connect()"," * .use(connect.favicon('public/favicon.ico))"," *"," * @param {String} path"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","module.exports = function favicon(path, options){"," var options = options || {}"," , path = path || __dirname + '/../public/favicon.ico'"," , maxAge = options.maxAge || 86400000"," , icon; // favicon cache",""," return function favicon(req, res, next){"," if ('/favicon.ico' == req.url) {"," if (icon) {"," res.writeHead(200, icon.headers);"," res.end(icon.body);"," } else {"," fs.readFile(path, function(err, buf){"," if (err) return next(err);"," icon = {"," headers: {"," 'Content-Type': 'image/x-icon'"," , 'Content-Length': buf.length"," , 'ETag': '\"' + utils.md5(buf) + '\"'"," , 'Cache-Control': 'public, max-age=' + (maxAge / 1000)"," },"," body: buf"," };"," res.writeHead(200, icon.headers);"," res.end(icon.body);"," });"," }"," } else {"," next();"," }"," };","};"];

View File

@@ -0,0 +1,117 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/json.js']) {
_$jscoverage['middleware/json.js'] = [];
_$jscoverage['middleware/json.js'][13] = 0;
_$jscoverage['middleware/json.js'][20] = 0;
_$jscoverage['middleware/json.js'][21] = 0;
_$jscoverage['middleware/json.js'][41] = 0;
_$jscoverage['middleware/json.js'][42] = 0;
_$jscoverage['middleware/json.js'][45] = 0;
_$jscoverage['middleware/json.js'][49] = 0;
_$jscoverage['middleware/json.js'][50] = 0;
_$jscoverage['middleware/json.js'][51] = 0;
_$jscoverage['middleware/json.js'][53] = 0;
_$jscoverage['middleware/json.js'][56] = 0;
_$jscoverage['middleware/json.js'][59] = 0;
_$jscoverage['middleware/json.js'][62] = 0;
_$jscoverage['middleware/json.js'][63] = 0;
_$jscoverage['middleware/json.js'][64] = 0;
_$jscoverage['middleware/json.js'][65] = 0;
_$jscoverage['middleware/json.js'][66] = 0;
_$jscoverage['middleware/json.js'][67] = 0;
_$jscoverage['middleware/json.js'][68] = 0;
_$jscoverage['middleware/json.js'][70] = 0;
_$jscoverage['middleware/json.js'][71] = 0;
_$jscoverage['middleware/json.js'][74] = 0;
_$jscoverage['middleware/json.js'][75] = 0;
_$jscoverage['middleware/json.js'][76] = 0;
_$jscoverage['middleware/json.js'][77] = 0;
_$jscoverage['middleware/json.js'][79] = 0;
_$jscoverage['middleware/json.js'][80] = 0;
_$jscoverage['middleware/json.js'][81] = 0;
}
_$jscoverage['middleware/json.js'][13]++;
var utils = require("../utils"), _limit = require("./limit");
_$jscoverage['middleware/json.js'][20]++;
function noop(req, res, next) {
_$jscoverage['middleware/json.js'][21]++;
next();
}
_$jscoverage['middleware/json.js'][41]++;
exports = module.exports = (function (options) {
_$jscoverage['middleware/json.js'][42]++;
var options = options || {}, strict = options.strict !== false;
_$jscoverage['middleware/json.js'][45]++;
var limit = options.limit? _limit(options.limit): noop;
_$jscoverage['middleware/json.js'][49]++;
return (function json(req, res, next) {
_$jscoverage['middleware/json.js'][50]++;
if (req._body) {
_$jscoverage['middleware/json.js'][50]++;
return next();
}
_$jscoverage['middleware/json.js'][51]++;
req.body = req.body || {};
_$jscoverage['middleware/json.js'][53]++;
if (! utils.hasBody(req)) {
_$jscoverage['middleware/json.js'][53]++;
return next();
}
_$jscoverage['middleware/json.js'][56]++;
if ("application/json" != utils.mime(req)) {
_$jscoverage['middleware/json.js'][56]++;
return next();
}
_$jscoverage['middleware/json.js'][59]++;
req._body = true;
_$jscoverage['middleware/json.js'][62]++;
limit(req, res, (function (err) {
_$jscoverage['middleware/json.js'][63]++;
if (err) {
_$jscoverage['middleware/json.js'][63]++;
return next(err);
}
_$jscoverage['middleware/json.js'][64]++;
var buf = "";
_$jscoverage['middleware/json.js'][65]++;
req.setEncoding("utf8");
_$jscoverage['middleware/json.js'][66]++;
req.on("data", (function (chunk) {
_$jscoverage['middleware/json.js'][66]++;
buf += chunk;
}));
_$jscoverage['middleware/json.js'][67]++;
req.on("end", (function () {
_$jscoverage['middleware/json.js'][68]++;
var first = buf.trim()[0];
_$jscoverage['middleware/json.js'][70]++;
if (0 == buf.length) {
_$jscoverage['middleware/json.js'][71]++;
return next(utils.error(400, "invalid json, empty body"));
}
_$jscoverage['middleware/json.js'][74]++;
if (strict && "{" != first && "[" != first) {
_$jscoverage['middleware/json.js'][74]++;
return next(utils.error(400, "invalid json"));
}
_$jscoverage['middleware/json.js'][75]++;
try {
_$jscoverage['middleware/json.js'][76]++;
req.body = JSON.parse(buf, options.reviver);
_$jscoverage['middleware/json.js'][77]++;
next();
}
catch (err) {
_$jscoverage['middleware/json.js'][79]++;
err.body = buf;
_$jscoverage['middleware/json.js'][80]++;
err.status = 400;
_$jscoverage['middleware/json.js'][81]++;
next(err);
}
}));
}));
});
});
_$jscoverage['middleware/json.js'].source = ["","/*!"," * Connect - json"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils')"," , _limit = require('./limit');","","/**"," * noop middleware."," */","","function noop(req, res, next) {"," next();","}","","/**"," * JSON:"," *"," * Parse JSON request bodies, providing the"," * parsed object as `req.body`."," *"," * Options:"," *"," * - `strict` when `false` anything `JSON.parse()` accepts will be parsed"," * - `reviver` used as the second \"reviver\" argument for JSON.parse"," * - `limit` byte limit disabled by default"," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function(options){"," var options = options || {}"," , strict = options.strict !== false;",""," var limit = options.limit"," ? _limit(options.limit)"," : noop;",""," return function json(req, res, next) {"," if (req._body) return next();"," req.body = req.body || {};",""," if (!utils.hasBody(req)) return next();",""," // check Content-Type"," if ('application/json' != utils.mime(req)) return next();",""," // flag as parsed"," req._body = true;",""," // parse"," limit(req, res, function(err){"," if (err) return next(err);"," var buf = '';"," req.setEncoding('utf8');"," req.on('data', function(chunk){ buf += chunk });"," req.on('end', function(){"," var first = buf.trim()[0];",""," if (0 == buf.length) {"," return next(utils.error(400, 'invalid json, empty body'));"," }"," "," if (strict &amp;&amp; '{' != first &amp;&amp; '[' != first) return next(utils.error(400, 'invalid json'));"," try {"," req.body = JSON.parse(buf, options.reviver);"," next();"," } catch (err){"," err.body = buf;"," err.status = 400;"," next(err);"," }"," });"," });"," }","};"];

View File

@@ -0,0 +1,63 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/limit.js']) {
_$jscoverage['middleware/limit.js'] = [];
_$jscoverage['middleware/limit.js'][12] = 0;
_$jscoverage['middleware/limit.js'][31] = 0;
_$jscoverage['middleware/limit.js'][32] = 0;
_$jscoverage['middleware/limit.js'][33] = 0;
_$jscoverage['middleware/limit.js'][34] = 0;
_$jscoverage['middleware/limit.js'][35] = 0;
_$jscoverage['middleware/limit.js'][41] = 0;
_$jscoverage['middleware/limit.js'][42] = 0;
_$jscoverage['middleware/limit.js'][45] = 0;
_$jscoverage['middleware/limit.js'][48] = 0;
_$jscoverage['middleware/limit.js'][49] = 0;
_$jscoverage['middleware/limit.js'][50] = 0;
_$jscoverage['middleware/limit.js'][53] = 0;
}
_$jscoverage['middleware/limit.js'][12]++;
var utils = require("../utils");
_$jscoverage['middleware/limit.js'][31]++;
module.exports = (function limit(bytes) {
_$jscoverage['middleware/limit.js'][32]++;
if ("string" == typeof bytes) {
_$jscoverage['middleware/limit.js'][32]++;
bytes = utils.parseBytes(bytes);
}
_$jscoverage['middleware/limit.js'][33]++;
if ("number" != typeof bytes) {
_$jscoverage['middleware/limit.js'][33]++;
throw new Error("limit() bytes required");
}
_$jscoverage['middleware/limit.js'][34]++;
return (function limit(req, res, next) {
_$jscoverage['middleware/limit.js'][35]++;
var received = 0, len = req.headers["content-length"]? parseInt(req.headers["content-length"], 10): null;
_$jscoverage['middleware/limit.js'][41]++;
if (req._limit) {
_$jscoverage['middleware/limit.js'][41]++;
return next();
}
_$jscoverage['middleware/limit.js'][42]++;
req._limit = true;
_$jscoverage['middleware/limit.js'][45]++;
if (len && len > bytes) {
_$jscoverage['middleware/limit.js'][45]++;
return next(utils.error(413));
}
_$jscoverage['middleware/limit.js'][48]++;
req.on("data", (function (chunk) {
_$jscoverage['middleware/limit.js'][49]++;
received += chunk.length;
_$jscoverage['middleware/limit.js'][50]++;
if (received > bytes) {
_$jscoverage['middleware/limit.js'][50]++;
req.destroy();
}
}));
_$jscoverage['middleware/limit.js'][53]++;
next();
});
});
_$jscoverage['middleware/limit.js'].source = ["","/*!"," * Connect - limit"," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils');","","/**"," * Limit:"," *"," * 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 = utils.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 &amp;&amp; len &gt; bytes) return next(utils.error(413));",""," // limit"," req.on('data', function(chunk){"," received += chunk.length;"," if (received &gt; bytes) req.destroy();"," });",""," next();"," };","};"];

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,42 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/methodOverride.js']) {
_$jscoverage['middleware/methodOverride.js'] = [];
_$jscoverage['middleware/methodOverride.js'][23] = 0;
_$jscoverage['middleware/methodOverride.js'][24] = 0;
_$jscoverage['middleware/methodOverride.js'][25] = 0;
_$jscoverage['middleware/methodOverride.js'][26] = 0;
_$jscoverage['middleware/methodOverride.js'][29] = 0;
_$jscoverage['middleware/methodOverride.js'][30] = 0;
_$jscoverage['middleware/methodOverride.js'][31] = 0;
_$jscoverage['middleware/methodOverride.js'][33] = 0;
_$jscoverage['middleware/methodOverride.js'][34] = 0;
_$jscoverage['middleware/methodOverride.js'][37] = 0;
}
_$jscoverage['middleware/methodOverride.js'][23]++;
module.exports = (function methodOverride(key) {
_$jscoverage['middleware/methodOverride.js'][24]++;
key = key || "_method";
_$jscoverage['middleware/methodOverride.js'][25]++;
return (function methodOverride(req, res, next) {
_$jscoverage['middleware/methodOverride.js'][26]++;
req.originalMethod = req.originalMethod || req.method;
_$jscoverage['middleware/methodOverride.js'][29]++;
if (req.body && key in req.body) {
_$jscoverage['middleware/methodOverride.js'][30]++;
req.method = req.body[key].toUpperCase();
_$jscoverage['middleware/methodOverride.js'][31]++;
delete req.body[key];
}
else {
_$jscoverage['middleware/methodOverride.js'][33]++;
if (req.headers["x-http-method-override"]) {
_$jscoverage['middleware/methodOverride.js'][34]++;
req.method = req.headers["x-http-method-override"].toUpperCase();
}
}
_$jscoverage['middleware/methodOverride.js'][37]++;
next();
});
});
_$jscoverage['middleware/methodOverride.js'].source = ["","/*!"," * Connect - methodOverride"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Method Override:"," * "," * Provides faux HTTP method support."," * "," * Pass an optional `key` to use when checking for"," * a method override, othewise defaults to _\\_method_."," * The original method is available via `req.originalMethod`."," *"," * @param {String} key"," * @return {Function}"," * @api public"," */","","module.exports = function methodOverride(key){"," key = key || \"_method\";"," return function methodOverride(req, res, next) {"," req.originalMethod = req.originalMethod || req.method;",""," // req.body"," if (req.body &amp;&amp; key in req.body) {"," req.method = req.body[key].toUpperCase();"," delete req.body[key];"," // check X-HTTP-Method-Override"," } else if (req.headers['x-http-method-override']) {"," req.method = req.headers['x-http-method-override'].toUpperCase();"," }"," "," next();"," };","};",""];

View File

@@ -0,0 +1,183 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/multipart.js']) {
_$jscoverage['middleware/multipart.js'] = [];
_$jscoverage['middleware/multipart.js'][12] = 0;
_$jscoverage['middleware/multipart.js'][21] = 0;
_$jscoverage['middleware/multipart.js'][22] = 0;
_$jscoverage['middleware/multipart.js'][52] = 0;
_$jscoverage['middleware/multipart.js'][53] = 0;
_$jscoverage['middleware/multipart.js'][55] = 0;
_$jscoverage['middleware/multipart.js'][59] = 0;
_$jscoverage['middleware/multipart.js'][60] = 0;
_$jscoverage['middleware/multipart.js'][61] = 0;
_$jscoverage['middleware/multipart.js'][62] = 0;
_$jscoverage['middleware/multipart.js'][64] = 0;
_$jscoverage['middleware/multipart.js'][67] = 0;
_$jscoverage['middleware/multipart.js'][70] = 0;
_$jscoverage['middleware/multipart.js'][73] = 0;
_$jscoverage['middleware/multipart.js'][76] = 0;
_$jscoverage['middleware/multipart.js'][77] = 0;
_$jscoverage['middleware/multipart.js'][79] = 0;
_$jscoverage['middleware/multipart.js'][84] = 0;
_$jscoverage['middleware/multipart.js'][85] = 0;
_$jscoverage['middleware/multipart.js'][88] = 0;
_$jscoverage['middleware/multipart.js'][89] = 0;
_$jscoverage['middleware/multipart.js'][90] = 0;
_$jscoverage['middleware/multipart.js'][91] = 0;
_$jscoverage['middleware/multipart.js'][92] = 0;
_$jscoverage['middleware/multipart.js'][94] = 0;
_$jscoverage['middleware/multipart.js'][98] = 0;
_$jscoverage['middleware/multipart.js'][99] = 0;
_$jscoverage['middleware/multipart.js'][102] = 0;
_$jscoverage['middleware/multipart.js'][103] = 0;
_$jscoverage['middleware/multipart.js'][106] = 0;
_$jscoverage['middleware/multipart.js'][107] = 0;
_$jscoverage['middleware/multipart.js'][108] = 0;
_$jscoverage['middleware/multipart.js'][109] = 0;
_$jscoverage['middleware/multipart.js'][111] = 0;
_$jscoverage['middleware/multipart.js'][114] = 0;
_$jscoverage['middleware/multipart.js'][115] = 0;
_$jscoverage['middleware/multipart.js'][116] = 0;
_$jscoverage['middleware/multipart.js'][117] = 0;
_$jscoverage['middleware/multipart.js'][118] = 0;
_$jscoverage['middleware/multipart.js'][119] = 0;
_$jscoverage['middleware/multipart.js'][121] = 0;
_$jscoverage['middleware/multipart.js'][125] = 0;
_$jscoverage['middleware/multipart.js'][127] = 0;
_$jscoverage['middleware/multipart.js'][128] = 0;
_$jscoverage['middleware/multipart.js'][129] = 0;
}
_$jscoverage['middleware/multipart.js'][12]++;
var formidable = require("formidable"), _limit = require("./limit"), utils = require("../utils"), qs = require("qs");
_$jscoverage['middleware/multipart.js'][21]++;
function noop(req, res, next) {
_$jscoverage['middleware/multipart.js'][22]++;
next();
}
_$jscoverage['middleware/multipart.js'][52]++;
exports = module.exports = (function (options) {
_$jscoverage['middleware/multipart.js'][53]++;
options = options || {};
_$jscoverage['middleware/multipart.js'][55]++;
var limit = options.limit? _limit(options.limit): noop;
_$jscoverage['middleware/multipart.js'][59]++;
return (function multipart(req, res, next) {
_$jscoverage['middleware/multipart.js'][60]++;
if (req._body) {
_$jscoverage['middleware/multipart.js'][60]++;
return next();
}
_$jscoverage['middleware/multipart.js'][61]++;
req.body = req.body || {};
_$jscoverage['middleware/multipart.js'][62]++;
req.files = req.files || {};
_$jscoverage['middleware/multipart.js'][64]++;
if (! utils.hasBody(req)) {
_$jscoverage['middleware/multipart.js'][64]++;
return next();
}
_$jscoverage['middleware/multipart.js'][67]++;
if ("GET" == req.method || "HEAD" == req.method) {
_$jscoverage['middleware/multipart.js'][67]++;
return next();
}
_$jscoverage['middleware/multipart.js'][70]++;
if ("multipart/form-data" != utils.mime(req)) {
_$jscoverage['middleware/multipart.js'][70]++;
return next();
}
_$jscoverage['middleware/multipart.js'][73]++;
req._body = true;
_$jscoverage['middleware/multipart.js'][76]++;
limit(req, res, (function (err) {
_$jscoverage['middleware/multipart.js'][77]++;
if (err) {
_$jscoverage['middleware/multipart.js'][77]++;
return next(err);
}
_$jscoverage['middleware/multipart.js'][79]++;
var form = new formidable.IncomingForm(), data = {}, files = {}, done;
_$jscoverage['middleware/multipart.js'][84]++;
Object.keys(options).forEach((function (key) {
_$jscoverage['middleware/multipart.js'][85]++;
form[key] = options[key];
}));
_$jscoverage['middleware/multipart.js'][88]++;
function ondata(name, val, data) {
_$jscoverage['middleware/multipart.js'][89]++;
if (Array.isArray(data[name])) {
_$jscoverage['middleware/multipart.js'][90]++;
data[name].push(val);
}
else {
_$jscoverage['middleware/multipart.js'][91]++;
if (data[name]) {
_$jscoverage['middleware/multipart.js'][92]++;
data[name] = [data[name], val];
}
else {
_$jscoverage['middleware/multipart.js'][94]++;
data[name] = val;
}
}
}
_$jscoverage['middleware/multipart.js'][98]++;
form.on("field", (function (name, val) {
_$jscoverage['middleware/multipart.js'][99]++;
ondata(name, val, data);
}));
_$jscoverage['middleware/multipart.js'][102]++;
form.on("file", (function (name, val) {
_$jscoverage['middleware/multipart.js'][103]++;
ondata(name, val, files);
}));
_$jscoverage['middleware/multipart.js'][106]++;
form.on("error", (function (err) {
_$jscoverage['middleware/multipart.js'][107]++;
if (! options.defer) {
_$jscoverage['middleware/multipart.js'][108]++;
err.status = 400;
_$jscoverage['middleware/multipart.js'][109]++;
next(err);
}
_$jscoverage['middleware/multipart.js'][111]++;
done = true;
}));
_$jscoverage['middleware/multipart.js'][114]++;
form.on("end", (function () {
_$jscoverage['middleware/multipart.js'][115]++;
if (done) {
_$jscoverage['middleware/multipart.js'][115]++;
return;
}
_$jscoverage['middleware/multipart.js'][116]++;
try {
_$jscoverage['middleware/multipart.js'][117]++;
req.body = qs.parse(data);
_$jscoverage['middleware/multipart.js'][118]++;
req.files = qs.parse(files);
_$jscoverage['middleware/multipart.js'][119]++;
if (! options.defer) {
_$jscoverage['middleware/multipart.js'][119]++;
next();
}
}
catch (err) {
_$jscoverage['middleware/multipart.js'][121]++;
form.emit("error", err);
}
}));
_$jscoverage['middleware/multipart.js'][125]++;
form.parse(req);
_$jscoverage['middleware/multipart.js'][127]++;
if (options.defer) {
_$jscoverage['middleware/multipart.js'][128]++;
req.form = form;
_$jscoverage['middleware/multipart.js'][129]++;
next();
}
}));
});
});
_$jscoverage['middleware/multipart.js'].source = ["/*!"," * Connect - multipart"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var formidable = require('formidable')"," , _limit = require('./limit')"," , utils = require('../utils')"," , qs = require('qs');","","/**"," * noop middleware."," */","","function noop(req, res, next) {"," next();","}","","/**"," * Multipart:"," * "," * Parse multipart/form-data request bodies,"," * providing the parsed object as `req.body`"," * and `req.files`."," *"," * Configuration:"," *"," * The options passed are merged with [formidable](https://github.com/felixge/node-formidable)'s"," * `IncomingForm` 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 none"," * - `defer` defers processing and exposes the Formidable 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\" event, for example."," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function(options){"," options = options || {};",""," var limit = options.limit"," ? _limit(options.limit)"," : noop;",""," return function multipart(req, res, next) {"," if (req._body) return next();"," req.body = req.body || {};"," req.files = req.files || {};",""," if (!utils.hasBody(req)) return next();",""," // ignore GET"," if ('GET' == req.method || 'HEAD' == req.method) return next();",""," // check Content-Type"," if ('multipart/form-data' != utils.mime(req)) return next();",""," // flag as parsed"," req._body = true;",""," // parse"," limit(req, res, function(err){"," if (err) return next(err);",""," var form = new formidable.IncomingForm"," , 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);"," });",""," form.on('file', function(name, val){"," ondata(name, val, files);"," });",""," form.on('error', function(err){"," if (!options.defer) {"," err.status = 400;"," next(err);"," }"," done = true;"," });",""," form.on('end', function(){"," if (done) return;"," try {"," req.body = qs.parse(data);"," req.files = qs.parse(files);"," if (!options.defer) next();"," } catch (err) {"," form.emit('error', err);"," }"," });",""," form.parse(req);",""," if (options.defer) {"," req.form = form;"," next();"," }"," });"," }","};"];

View File

@@ -0,0 +1,27 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/query.js']) {
_$jscoverage['middleware/query.js'] = [];
_$jscoverage['middleware/query.js'][12] = 0;
_$jscoverage['middleware/query.js'][36] = 0;
_$jscoverage['middleware/query.js'][37] = 0;
_$jscoverage['middleware/query.js'][38] = 0;
_$jscoverage['middleware/query.js'][39] = 0;
_$jscoverage['middleware/query.js'][44] = 0;
}
_$jscoverage['middleware/query.js'][12]++;
var qs = require("qs"), parse = require("../utils").parseUrl;
_$jscoverage['middleware/query.js'][36]++;
module.exports = (function query(options) {
_$jscoverage['middleware/query.js'][37]++;
return (function query(req, res, next) {
_$jscoverage['middleware/query.js'][38]++;
if (! req.query) {
_$jscoverage['middleware/query.js'][39]++;
req.query = ~ req.url.indexOf("?")? qs.parse(parse(req).query, options): {};
}
_$jscoverage['middleware/query.js'][44]++;
next();
});
});
_$jscoverage['middleware/query.js'].source = ["/*!"," * Connect - query"," * Copyright(c) 2011 TJ Holowaychuk"," * Copyright(c) 2011 Sencha Inc."," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var qs = require('qs')"," , parse = require('../utils').parseUrl;","","/**"," * Query:"," *"," * Automatically parse the query-string when available,"," * populating the `req.query` object."," *"," * 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(parse(req).query, options)"," : {};"," }",""," next();"," };","};"];

View File

@@ -0,0 +1,39 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/responseTime.js']) {
_$jscoverage['middleware/responseTime.js'] = [];
_$jscoverage['middleware/responseTime.js'][18] = 0;
_$jscoverage['middleware/responseTime.js'][19] = 0;
_$jscoverage['middleware/responseTime.js'][20] = 0;
_$jscoverage['middleware/responseTime.js'][22] = 0;
_$jscoverage['middleware/responseTime.js'][23] = 0;
_$jscoverage['middleware/responseTime.js'][25] = 0;
_$jscoverage['middleware/responseTime.js'][26] = 0;
_$jscoverage['middleware/responseTime.js'][27] = 0;
_$jscoverage['middleware/responseTime.js'][30] = 0;
}
_$jscoverage['middleware/responseTime.js'][18]++;
module.exports = (function responseTime() {
_$jscoverage['middleware/responseTime.js'][19]++;
return (function (req, res, next) {
_$jscoverage['middleware/responseTime.js'][20]++;
var start = new Date();
_$jscoverage['middleware/responseTime.js'][22]++;
if (res._responseTime) {
_$jscoverage['middleware/responseTime.js'][22]++;
return next();
}
_$jscoverage['middleware/responseTime.js'][23]++;
res._responseTime = true;
_$jscoverage['middleware/responseTime.js'][25]++;
res.on("header", (function () {
_$jscoverage['middleware/responseTime.js'][26]++;
var duration = new Date() - start;
_$jscoverage['middleware/responseTime.js'][27]++;
res.setHeader("X-Response-Time", duration + "ms");
}));
_$jscoverage['middleware/responseTime.js'][30]++;
next();
});
});
_$jscoverage['middleware/responseTime.js'].source = ["","/*!"," * Connect - responseTime"," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Reponse time:"," *"," * Adds the `X-Response-Time` header displaying the response"," * duration in milliseconds."," *"," * @return {Function}"," * @api public"," */","","module.exports = function responseTime(){"," return function(req, res, next){"," var start = new Date;",""," if (res._responseTime) return next();"," res._responseTime = true;",""," res.on('header', function(){"," var duration = new Date - start;"," res.setHeader('X-Response-Time', duration + 'ms');"," });",""," next();"," };","};"];

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,65 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/session/cookie.js']) {
_$jscoverage['middleware/session/cookie.js'] = [];
_$jscoverage['middleware/session/cookie.js'][13] = 0;
_$jscoverage['middleware/session/cookie.js'][24] = 0;
_$jscoverage['middleware/session/cookie.js'][25] = 0;
_$jscoverage['middleware/session/cookie.js'][26] = 0;
_$jscoverage['middleware/session/cookie.js'][27] = 0;
_$jscoverage['middleware/session/cookie.js'][28] = 0;
_$jscoverage['middleware/session/cookie.js'][29] = 0;
_$jscoverage['middleware/session/cookie.js'][38] = 0;
_$jscoverage['middleware/session/cookie.js'][48] = 0;
_$jscoverage['middleware/session/cookie.js'][49] = 0;
_$jscoverage['middleware/session/cookie.js'][60] = 0;
_$jscoverage['middleware/session/cookie.js'][71] = 0;
_$jscoverage['middleware/session/cookie.js'][84] = 0;
_$jscoverage['middleware/session/cookie.js'][97] = 0;
_$jscoverage['middleware/session/cookie.js'][115] = 0;
_$jscoverage['middleware/session/cookie.js'][126] = 0;
}
_$jscoverage['middleware/session/cookie.js'][13]++;
var utils = require("../../utils"), cookie = require("cookie");
_$jscoverage['middleware/session/cookie.js'][24]++;
var Cookie = module.exports = (function Cookie(options) {
_$jscoverage['middleware/session/cookie.js'][25]++;
this.path = "/";
_$jscoverage['middleware/session/cookie.js'][26]++;
this.maxAge = null;
_$jscoverage['middleware/session/cookie.js'][27]++;
this.httpOnly = true;
_$jscoverage['middleware/session/cookie.js'][28]++;
if (options) {
_$jscoverage['middleware/session/cookie.js'][28]++;
utils.merge(this, options);
}
_$jscoverage['middleware/session/cookie.js'][29]++;
this.originalMaxAge = undefined == this.originalMaxAge? this.maxAge: this.originalMaxAge;
});
_$jscoverage['middleware/session/cookie.js'][38]++;
Cookie.prototype = {set expires (date) {
_$jscoverage['middleware/session/cookie.js'][48]++;
this._expires = date;
_$jscoverage['middleware/session/cookie.js'][49]++;
this.originalMaxAge = this.maxAge;
}, get expires () {
_$jscoverage['middleware/session/cookie.js'][60]++;
return this._expires;
}, set maxAge (ms) {
_$jscoverage['middleware/session/cookie.js'][71]++;
this.expires = "number" == typeof ms? new Date(Date.now() + ms): ms;
}, get maxAge () {
_$jscoverage['middleware/session/cookie.js'][84]++;
return this.expires instanceof Date? this.expires.valueOf() - Date.now(): this.expires;
}, get data () {
_$jscoverage['middleware/session/cookie.js'][97]++;
return ({originalMaxAge: this.originalMaxAge, expires: this._expires, secure: this.secure, httpOnly: this.httpOnly, domain: this.domain, path: this.path});
}, serialize: (function (name, val) {
_$jscoverage['middleware/session/cookie.js'][115]++;
return cookie.serialize(name, val, this.data);
}), toJSON: (function () {
_$jscoverage['middleware/session/cookie.js'][126]++;
return this.data;
})};
_$jscoverage['middleware/session/cookie.js'].source = ["","/*!"," * Connect - session - Cookie"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../../utils')"," , cookie = require('cookie');","","/**"," * Initialize a new `Cookie` with the given `options`."," *"," * @param {IncomingMessage} req"," * @param {Object} options"," * @api private"," */","","var Cookie = module.exports = function Cookie(options) {"," this.path = '/';"," this.maxAge = null;"," this.httpOnly = true;"," if (options) utils.merge(this, options);"," this.originalMaxAge = undefined == this.originalMaxAge"," ? this.maxAge"," : this.originalMaxAge;","};","","/*!"," * Prototype."," */","","Cookie.prototype = {",""," /**"," * Set expires `date`."," *"," * @param {Date} date"," * @api public"," */"," "," set expires(date) {"," this._expires = date;"," this.originalMaxAge = this.maxAge;"," },",""," /**"," * Get expires `date`."," *"," * @return {Date}"," * @api public"," */",""," get expires() {"," return this._expires;"," },"," "," /**"," * Set expires via max-age in `ms`."," *"," * @param {Number} ms"," * @api public"," */"," "," set maxAge(ms) {"," this.expires = 'number' == typeof ms"," ? new Date(Date.now() + ms)"," : ms;"," },",""," /**"," * Get expires max-age in `ms`."," *"," * @return {Number}"," * @api public"," */",""," get maxAge() {"," return this.expires instanceof Date"," ? this.expires.valueOf() - Date.now()"," : this.expires;"," },",""," /**"," * Return cookie data object."," *"," * @return {Object}"," * @api private"," */",""," get data() {"," return {"," originalMaxAge: this.originalMaxAge"," , expires: this._expires"," , secure: this.secure"," , httpOnly: this.httpOnly"," , domain: this.domain"," , path: this.path"," }"," },",""," /**"," * Return a serialized cookie string."," *"," * @return {String}"," * @api public"," */",""," serialize: function(name, val){"," return cookie.serialize(name, val, this.data);"," },",""," /**"," * Return JSON representation of this cookie."," *"," * @return {Object}"," * @api private"," */"," "," toJSON: function(){"," return this.data;"," }","};"];

View File

@@ -0,0 +1,128 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/session/memory.js']) {
_$jscoverage['middleware/session/memory.js'] = [];
_$jscoverage['middleware/session/memory.js'][13] = 0;
_$jscoverage['middleware/session/memory.js'][21] = 0;
_$jscoverage['middleware/session/memory.js'][22] = 0;
_$jscoverage['middleware/session/memory.js'][29] = 0;
_$jscoverage['middleware/session/memory.js'][39] = 0;
_$jscoverage['middleware/session/memory.js'][40] = 0;
_$jscoverage['middleware/session/memory.js'][41] = 0;
_$jscoverage['middleware/session/memory.js'][42] = 0;
_$jscoverage['middleware/session/memory.js'][44] = 0;
_$jscoverage['middleware/session/memory.js'][45] = 0;
_$jscoverage['middleware/session/memory.js'][46] = 0;
_$jscoverage['middleware/session/memory.js'][49] = 0;
_$jscoverage['middleware/session/memory.js'][50] = 0;
_$jscoverage['middleware/session/memory.js'][52] = 0;
_$jscoverage['middleware/session/memory.js'][55] = 0;
_$jscoverage['middleware/session/memory.js'][69] = 0;
_$jscoverage['middleware/session/memory.js'][70] = 0;
_$jscoverage['middleware/session/memory.js'][71] = 0;
_$jscoverage['middleware/session/memory.js'][72] = 0;
_$jscoverage['middleware/session/memory.js'][73] = 0;
_$jscoverage['middleware/session/memory.js'][84] = 0;
_$jscoverage['middleware/session/memory.js'][85] = 0;
_$jscoverage['middleware/session/memory.js'][86] = 0;
_$jscoverage['middleware/session/memory.js'][87] = 0;
_$jscoverage['middleware/session/memory.js'][88] = 0;
_$jscoverage['middleware/session/memory.js'][99] = 0;
_$jscoverage['middleware/session/memory.js'][100] = 0;
_$jscoverage['middleware/session/memory.js'][102] = 0;
_$jscoverage['middleware/session/memory.js'][103] = 0;
_$jscoverage['middleware/session/memory.js'][105] = 0;
_$jscoverage['middleware/session/memory.js'][115] = 0;
_$jscoverage['middleware/session/memory.js'][116] = 0;
_$jscoverage['middleware/session/memory.js'][117] = 0;
_$jscoverage['middleware/session/memory.js'][127] = 0;
_$jscoverage['middleware/session/memory.js'][128] = 0;
}
_$jscoverage['middleware/session/memory.js'][13]++;
var Store = require("./store");
_$jscoverage['middleware/session/memory.js'][21]++;
var MemoryStore = module.exports = (function MemoryStore() {
_$jscoverage['middleware/session/memory.js'][22]++;
this.sessions = {};
});
_$jscoverage['middleware/session/memory.js'][29]++;
MemoryStore.prototype.__proto__ = Store.prototype;
_$jscoverage['middleware/session/memory.js'][39]++;
MemoryStore.prototype.get = (function (sid, fn) {
_$jscoverage['middleware/session/memory.js'][40]++;
var self = this;
_$jscoverage['middleware/session/memory.js'][41]++;
process.nextTick((function () {
_$jscoverage['middleware/session/memory.js'][42]++;
var expires, sess = self.sessions[sid];
_$jscoverage['middleware/session/memory.js'][44]++;
if (sess) {
_$jscoverage['middleware/session/memory.js'][45]++;
sess = JSON.parse(sess);
_$jscoverage['middleware/session/memory.js'][46]++;
expires = "string" == typeof sess.cookie.expires? new Date(sess.cookie.expires): sess.cookie.expires;
_$jscoverage['middleware/session/memory.js'][49]++;
if (! expires || new Date() < expires) {
_$jscoverage['middleware/session/memory.js'][50]++;
fn(null, sess);
}
else {
_$jscoverage['middleware/session/memory.js'][52]++;
self.destroy(sid, fn);
}
}
else {
_$jscoverage['middleware/session/memory.js'][55]++;
fn();
}
}));
});
_$jscoverage['middleware/session/memory.js'][69]++;
MemoryStore.prototype.set = (function (sid, sess, fn) {
_$jscoverage['middleware/session/memory.js'][70]++;
var self = this;
_$jscoverage['middleware/session/memory.js'][71]++;
process.nextTick((function () {
_$jscoverage['middleware/session/memory.js'][72]++;
self.sessions[sid] = JSON.stringify(sess);
_$jscoverage['middleware/session/memory.js'][73]++;
fn && fn();
}));
});
_$jscoverage['middleware/session/memory.js'][84]++;
MemoryStore.prototype.destroy = (function (sid, fn) {
_$jscoverage['middleware/session/memory.js'][85]++;
var self = this;
_$jscoverage['middleware/session/memory.js'][86]++;
process.nextTick((function () {
_$jscoverage['middleware/session/memory.js'][87]++;
delete self.sessions[sid];
_$jscoverage['middleware/session/memory.js'][88]++;
fn && fn();
}));
});
_$jscoverage['middleware/session/memory.js'][99]++;
MemoryStore.prototype.all = (function (fn) {
_$jscoverage['middleware/session/memory.js'][100]++;
var arr = [], keys = Object.keys(this.sessions);
_$jscoverage['middleware/session/memory.js'][102]++;
for (var i = 0, len = keys.length; i < len; ++i) {
_$jscoverage['middleware/session/memory.js'][103]++;
arr.push(this.sessions[keys[i]]);
}
_$jscoverage['middleware/session/memory.js'][105]++;
fn(null, arr);
});
_$jscoverage['middleware/session/memory.js'][115]++;
MemoryStore.prototype.clear = (function (fn) {
_$jscoverage['middleware/session/memory.js'][116]++;
this.sessions = {};
_$jscoverage['middleware/session/memory.js'][117]++;
fn && fn();
});
_$jscoverage['middleware/session/memory.js'][127]++;
MemoryStore.prototype.length = (function (fn) {
_$jscoverage['middleware/session/memory.js'][128]++;
fn(null, Object.keys(this.sessions).length);
});
_$jscoverage['middleware/session/memory.js'].source = ["","/*!"," * Connect - session - MemoryStore"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var Store = require('./store');","","/**"," * Initialize a new `MemoryStore`."," *"," * @api public"," */","","var MemoryStore = module.exports = function MemoryStore() {"," this.sessions = {};","};","","/**"," * Inherit from `Store.prototype`."," */","","MemoryStore.prototype.__proto__ = Store.prototype;","","/**"," * Attempt to fetch session by the given `sid`."," *"," * @param {String} sid"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.get = function(sid, fn){"," var self = this;"," process.nextTick(function(){"," var expires"," , sess = self.sessions[sid];"," if (sess) {"," sess = JSON.parse(sess);"," expires = 'string' == typeof sess.cookie.expires"," ? new Date(sess.cookie.expires)"," : sess.cookie.expires;"," if (!expires || new Date &lt; expires) {"," fn(null, sess);"," } else {"," self.destroy(sid, fn);"," }"," } else {"," fn();"," }"," });","};","","/**"," * Commit the given `sess` object associated with the given `sid`."," *"," * @param {String} sid"," * @param {Session} sess"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.set = function(sid, sess, fn){"," var self = this;"," process.nextTick(function(){"," self.sessions[sid] = JSON.stringify(sess);"," fn &amp;&amp; fn();"," });","};","","/**"," * Destroy the session associated with the given `sid`."," *"," * @param {String} sid"," * @api public"," */","","MemoryStore.prototype.destroy = function(sid, fn){"," var self = this;"," process.nextTick(function(){"," delete self.sessions[sid];"," fn &amp;&amp; fn();"," });","};","","/**"," * Invoke the given callback `fn` with all active sessions."," *"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.all = function(fn){"," var arr = []"," , keys = Object.keys(this.sessions);"," for (var i = 0, len = keys.length; i &lt; len; ++i) {"," arr.push(this.sessions[keys[i]]);"," }"," fn(null, arr);","};","","/**"," * Clear all sessions."," *"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.clear = function(fn){"," this.sessions = {};"," fn &amp;&amp; fn();","};","","/**"," * Fetch number of sessions."," *"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.length = function(fn){"," fn(null, Object.keys(this.sessions).length);","};"];

View File

@@ -0,0 +1,108 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/session/session.js']) {
_$jscoverage['middleware/session/session.js'] = [];
_$jscoverage['middleware/session/session.js'][13] = 0;
_$jscoverage['middleware/session/session.js'][23] = 0;
_$jscoverage['middleware/session/session.js'][24] = 0;
_$jscoverage['middleware/session/session.js'][25] = 0;
_$jscoverage['middleware/session/session.js'][26] = 0;
_$jscoverage['middleware/session/session.js'][38] = 0;
_$jscoverage['middleware/session/session.js'][39] = 0;
_$jscoverage['middleware/session/session.js'][49] = 0;
_$jscoverage['middleware/session/session.js'][50] = 0;
_$jscoverage['middleware/session/session.js'][51] = 0;
_$jscoverage['middleware/session/session.js'][62] = 0;
_$jscoverage['middleware/session/session.js'][63] = 0;
_$jscoverage['middleware/session/session.js'][64] = 0;
_$jscoverage['middleware/session/session.js'][79] = 0;
_$jscoverage['middleware/session/session.js'][80] = 0;
_$jscoverage['middleware/session/session.js'][82] = 0;
_$jscoverage['middleware/session/session.js'][83] = 0;
_$jscoverage['middleware/session/session.js'][84] = 0;
_$jscoverage['middleware/session/session.js'][85] = 0;
_$jscoverage['middleware/session/session.js'][86] = 0;
_$jscoverage['middleware/session/session.js'][88] = 0;
_$jscoverage['middleware/session/session.js'][99] = 0;
_$jscoverage['middleware/session/session.js'][100] = 0;
_$jscoverage['middleware/session/session.js'][101] = 0;
_$jscoverage['middleware/session/session.js'][102] = 0;
_$jscoverage['middleware/session/session.js'][113] = 0;
_$jscoverage['middleware/session/session.js'][114] = 0;
_$jscoverage['middleware/session/session.js'][115] = 0;
}
_$jscoverage['middleware/session/session.js'][13]++;
var utils = require("../../utils");
_$jscoverage['middleware/session/session.js'][23]++;
var Session = module.exports = (function Session(req, data) {
_$jscoverage['middleware/session/session.js'][24]++;
Object.defineProperty(this, "req", {value: req});
_$jscoverage['middleware/session/session.js'][25]++;
Object.defineProperty(this, "id", {value: req.sessionID});
_$jscoverage['middleware/session/session.js'][26]++;
if ("object" == typeof data) {
_$jscoverage['middleware/session/session.js'][26]++;
utils.merge(this, data);
}
});
_$jscoverage['middleware/session/session.js'][38]++;
Session.prototype.touch = (function () {
_$jscoverage['middleware/session/session.js'][39]++;
return this.resetMaxAge();
});
_$jscoverage['middleware/session/session.js'][49]++;
Session.prototype.resetMaxAge = (function () {
_$jscoverage['middleware/session/session.js'][50]++;
this.cookie.maxAge = this.cookie.originalMaxAge;
_$jscoverage['middleware/session/session.js'][51]++;
return this;
});
_$jscoverage['middleware/session/session.js'][62]++;
Session.prototype.save = (function (fn) {
_$jscoverage['middleware/session/session.js'][63]++;
this.req.sessionStore.set(this.id, this, fn || (function () {
}));
_$jscoverage['middleware/session/session.js'][64]++;
return this;
});
_$jscoverage['middleware/session/session.js'][79]++;
Session.prototype.reload = (function (fn) {
_$jscoverage['middleware/session/session.js'][80]++;
var req = this.req, store = this.req.sessionStore;
_$jscoverage['middleware/session/session.js'][82]++;
store.get(this.id, (function (err, sess) {
_$jscoverage['middleware/session/session.js'][83]++;
if (err) {
_$jscoverage['middleware/session/session.js'][83]++;
return fn(err);
}
_$jscoverage['middleware/session/session.js'][84]++;
if (! sess) {
_$jscoverage['middleware/session/session.js'][84]++;
return fn(new Error("failed to load session"));
}
_$jscoverage['middleware/session/session.js'][85]++;
store.createSession(req, sess);
_$jscoverage['middleware/session/session.js'][86]++;
fn();
}));
_$jscoverage['middleware/session/session.js'][88]++;
return this;
});
_$jscoverage['middleware/session/session.js'][99]++;
Session.prototype.destroy = (function (fn) {
_$jscoverage['middleware/session/session.js'][100]++;
delete this.req.session;
_$jscoverage['middleware/session/session.js'][101]++;
this.req.sessionStore.destroy(this.id, fn);
_$jscoverage['middleware/session/session.js'][102]++;
return this;
});
_$jscoverage['middleware/session/session.js'][113]++;
Session.prototype.regenerate = (function (fn) {
_$jscoverage['middleware/session/session.js'][114]++;
this.req.sessionStore.regenerate(this.req, fn);
_$jscoverage['middleware/session/session.js'][115]++;
return this;
});
_$jscoverage['middleware/session/session.js'].source = ["","/*!"," * Connect - session - Session"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../../utils');","","/**"," * Create a new `Session` with the given request and `data`."," *"," * @param {IncomingRequest} req"," * @param {Object} data"," * @api private"," */","","var Session = module.exports = function Session(req, data) {"," Object.defineProperty(this, 'req', { value: req });"," Object.defineProperty(this, 'id', { value: req.sessionID });"," if ('object' == typeof data) utils.merge(this, data);","};","","/**"," * Update reset `.cookie.maxAge` to prevent"," * the cookie from expiring when the"," * session is still active."," *"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.touch = function(){"," return this.resetMaxAge();","};","","/**"," * Reset `.maxAge` to `.originalMaxAge`."," *"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.resetMaxAge = function(){"," this.cookie.maxAge = this.cookie.originalMaxAge;"," return this;","};","","/**"," * Save the session data with optional callback `fn(err)`."," *"," * @param {Function} fn"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.save = function(fn){"," this.req.sessionStore.set(this.id, this, fn || function(){});"," return this;","};","","/**"," * Re-loads the session data _without_ altering"," * the maxAge properties. Invokes the callback `fn(err)`,"," * after which time if no exception has occurred the"," * `req.session` property will be a new `Session` object,"," * although representing the same session."," *"," * @param {Function} fn"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.reload = function(fn){"," var req = this.req"," , store = this.req.sessionStore;"," store.get(this.id, function(err, sess){"," if (err) return fn(err);"," if (!sess) return fn(new Error('failed to load session'));"," store.createSession(req, sess);"," fn();"," });"," return this;","};","","/**"," * Destroy `this` session."," *"," * @param {Function} fn"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.destroy = function(fn){"," delete this.req.session;"," this.req.sessionStore.destroy(this.id, fn);"," return this;","};","","/**"," * Regenerate this request's session."," *"," * @param {Function} fn"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.regenerate = function(fn){"," this.req.sessionStore.regenerate(this.req, fn);"," return this;","};"];

View File

@@ -0,0 +1,90 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/session/store.js']) {
_$jscoverage['middleware/session/store.js'] = [];
_$jscoverage['middleware/session/store.js'][13] = 0;
_$jscoverage['middleware/session/store.js'][23] = 0;
_$jscoverage['middleware/session/store.js'][29] = 0;
_$jscoverage['middleware/session/store.js'][39] = 0;
_$jscoverage['middleware/session/store.js'][40] = 0;
_$jscoverage['middleware/session/store.js'][41] = 0;
_$jscoverage['middleware/session/store.js'][42] = 0;
_$jscoverage['middleware/session/store.js'][43] = 0;
_$jscoverage['middleware/session/store.js'][56] = 0;
_$jscoverage['middleware/session/store.js'][57] = 0;
_$jscoverage['middleware/session/store.js'][58] = 0;
_$jscoverage['middleware/session/store.js'][59] = 0;
_$jscoverage['middleware/session/store.js'][60] = 0;
_$jscoverage['middleware/session/store.js'][61] = 0;
_$jscoverage['middleware/session/store.js'][62] = 0;
_$jscoverage['middleware/session/store.js'][63] = 0;
_$jscoverage['middleware/session/store.js'][76] = 0;
_$jscoverage['middleware/session/store.js'][77] = 0;
_$jscoverage['middleware/session/store.js'][79] = 0;
_$jscoverage['middleware/session/store.js'][80] = 0;
_$jscoverage['middleware/session/store.js'][81] = 0;
_$jscoverage['middleware/session/store.js'][82] = 0;
_$jscoverage['middleware/session/store.js'][83] = 0;
}
_$jscoverage['middleware/session/store.js'][13]++;
var EventEmitter = require("events").EventEmitter, Session = require("./session"), Cookie = require("./cookie");
_$jscoverage['middleware/session/store.js'][23]++;
var Store = module.exports = (function Store(options) {
});
_$jscoverage['middleware/session/store.js'][29]++;
Store.prototype.__proto__ = EventEmitter.prototype;
_$jscoverage['middleware/session/store.js'][39]++;
Store.prototype.regenerate = (function (req, fn) {
_$jscoverage['middleware/session/store.js'][40]++;
var self = this;
_$jscoverage['middleware/session/store.js'][41]++;
this.destroy(req.sessionID, (function (err) {
_$jscoverage['middleware/session/store.js'][42]++;
self.generate(req);
_$jscoverage['middleware/session/store.js'][43]++;
fn(err);
}));
});
_$jscoverage['middleware/session/store.js'][56]++;
Store.prototype.load = (function (sid, fn) {
_$jscoverage['middleware/session/store.js'][57]++;
var self = this;
_$jscoverage['middleware/session/store.js'][58]++;
this.get(sid, (function (err, sess) {
_$jscoverage['middleware/session/store.js'][59]++;
if (err) {
_$jscoverage['middleware/session/store.js'][59]++;
return fn(err);
}
_$jscoverage['middleware/session/store.js'][60]++;
if (! sess) {
_$jscoverage['middleware/session/store.js'][60]++;
return fn();
}
_$jscoverage['middleware/session/store.js'][61]++;
var req = {sessionID: sid, sessionStore: self};
_$jscoverage['middleware/session/store.js'][62]++;
sess = self.createSession(req, sess);
_$jscoverage['middleware/session/store.js'][63]++;
fn(null, sess);
}));
});
_$jscoverage['middleware/session/store.js'][76]++;
Store.prototype.createSession = (function (req, sess) {
_$jscoverage['middleware/session/store.js'][77]++;
var expires = sess.cookie.expires, orig = sess.cookie.originalMaxAge;
_$jscoverage['middleware/session/store.js'][79]++;
sess.cookie = new Cookie(sess.cookie);
_$jscoverage['middleware/session/store.js'][80]++;
if ("string" == typeof expires) {
_$jscoverage['middleware/session/store.js'][80]++;
sess.cookie.expires = new Date(expires);
}
_$jscoverage['middleware/session/store.js'][81]++;
sess.cookie.originalMaxAge = orig;
_$jscoverage['middleware/session/store.js'][82]++;
req.session = new Session(req, sess);
_$jscoverage['middleware/session/store.js'][83]++;
return req.session;
});
_$jscoverage['middleware/session/store.js'].source = ["","/*!"," * Connect - session - Store"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var EventEmitter = require('events').EventEmitter"," , Session = require('./session')"," , Cookie = require('./cookie');","","/**"," * Initialize abstract `Store`."," *"," * @api private"," */","","var Store = module.exports = function Store(options){};","","/**"," * Inherit from `EventEmitter.prototype`."," */","","Store.prototype.__proto__ = EventEmitter.prototype;","","/**"," * Re-generate the given requests's session."," *"," * @param {IncomingRequest} req"," * @return {Function} fn"," * @api public"," */","","Store.prototype.regenerate = function(req, fn){"," var self = this;"," this.destroy(req.sessionID, function(err){"," self.generate(req);"," fn(err);"," });","};","","/**"," * Load a `Session` instance via the given `sid`"," * and invoke the callback `fn(err, sess)`."," *"," * @param {String} sid"," * @param {Function} fn"," * @api public"," */","","Store.prototype.load = function(sid, fn){"," var self = this;"," this.get(sid, function(err, sess){"," if (err) return fn(err);"," if (!sess) return fn();"," var req = { sessionID: sid, sessionStore: self };"," sess = self.createSession(req, sess);"," fn(null, sess);"," });","};","","/**"," * Create session from JSON `sess` data."," *"," * @param {IncomingRequest} req"," * @param {Object} sess"," * @return {Session}"," * @api private"," */","","Store.prototype.createSession = function(req, sess){"," var expires = sess.cookie.expires"," , orig = sess.cookie.originalMaxAge;"," sess.cookie = new Cookie(sess.cookie);"," if ('string' == typeof expires) sess.cookie.expires = new Date(expires);"," sess.cookie.originalMaxAge = orig;"," req.session = new Session(req, sess);"," return req.session;","};"];

View File

@@ -0,0 +1,92 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/static.js']) {
_$jscoverage['middleware/static.js'] = [];
_$jscoverage['middleware/static.js'][13] = 0;
_$jscoverage['middleware/static.js'][45] = 0;
_$jscoverage['middleware/static.js'][46] = 0;
_$jscoverage['middleware/static.js'][49] = 0;
_$jscoverage['middleware/static.js'][52] = 0;
_$jscoverage['middleware/static.js'][54] = 0;
_$jscoverage['middleware/static.js'][55] = 0;
_$jscoverage['middleware/static.js'][56] = 0;
_$jscoverage['middleware/static.js'][57] = 0;
_$jscoverage['middleware/static.js'][59] = 0;
_$jscoverage['middleware/static.js'][60] = 0;
_$jscoverage['middleware/static.js'][61] = 0;
_$jscoverage['middleware/static.js'][64] = 0;
_$jscoverage['middleware/static.js'][65] = 0;
_$jscoverage['middleware/static.js'][66] = 0;
_$jscoverage['middleware/static.js'][67] = 0;
_$jscoverage['middleware/static.js'][68] = 0;
_$jscoverage['middleware/static.js'][69] = 0;
_$jscoverage['middleware/static.js'][72] = 0;
_$jscoverage['middleware/static.js'][73] = 0;
_$jscoverage['middleware/static.js'][74] = 0;
_$jscoverage['middleware/static.js'][77] = 0;
_$jscoverage['middleware/static.js'][94] = 0;
}
_$jscoverage['middleware/static.js'][13]++;
var send = require("send"), utils = require("../utils"), parse = utils.parseUrl, url = require("url");
_$jscoverage['middleware/static.js'][45]++;
exports = module.exports = (function static(root, options) {
_$jscoverage['middleware/static.js'][46]++;
options = options || {};
_$jscoverage['middleware/static.js'][49]++;
if (! root) {
_$jscoverage['middleware/static.js'][49]++;
throw new Error("static() root path required");
}
_$jscoverage['middleware/static.js'][52]++;
var redirect = false !== options.redirect;
_$jscoverage['middleware/static.js'][54]++;
return (function static(req, res, next) {
_$jscoverage['middleware/static.js'][55]++;
if ("GET" != req.method && "HEAD" != req.method) {
_$jscoverage['middleware/static.js'][55]++;
return next();
}
_$jscoverage['middleware/static.js'][56]++;
var path = parse(req).pathname;
_$jscoverage['middleware/static.js'][57]++;
var pause = utils.pause(req);
_$jscoverage['middleware/static.js'][59]++;
function resume() {
_$jscoverage['middleware/static.js'][60]++;
next();
_$jscoverage['middleware/static.js'][61]++;
pause.resume();
}
_$jscoverage['middleware/static.js'][64]++;
function directory() {
_$jscoverage['middleware/static.js'][65]++;
if (! redirect) {
_$jscoverage['middleware/static.js'][65]++;
return resume();
}
_$jscoverage['middleware/static.js'][66]++;
var pathname = url.parse(req.originalUrl).pathname;
_$jscoverage['middleware/static.js'][67]++;
res.statusCode = 301;
_$jscoverage['middleware/static.js'][68]++;
res.setHeader("Location", pathname + "/");
_$jscoverage['middleware/static.js'][69]++;
res.end("Redirecting to " + utils.escape(pathname) + "/");
}
_$jscoverage['middleware/static.js'][72]++;
function error(err) {
_$jscoverage['middleware/static.js'][73]++;
if (404 == err.status) {
_$jscoverage['middleware/static.js'][73]++;
return resume();
}
_$jscoverage['middleware/static.js'][74]++;
next(err);
}
_$jscoverage['middleware/static.js'][77]++;
send(req, path).maxage(options.maxAge || 0).root(root).hidden(options.hidden).on("error", error).on("directory", directory).pipe(res);
});
});
_$jscoverage['middleware/static.js'][94]++;
exports.mime = send.mime;
_$jscoverage['middleware/static.js'].source = ["","/*!"," * Connect - static"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var send = require('send')"," , utils = require('../utils')"," , parse = utils.parseUrl"," , url = require('url');","","/**"," * Static:"," *"," * Static file server with the given `root` path."," *"," * Examples:"," *"," * var oneDay = 86400000;"," *"," * connect()"," * .use(connect.static(__dirname + '/public'))"," *"," * connect()"," * .use(connect.static(__dirname + '/public', { maxAge: oneDay }))"," *"," * Options:"," *"," * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0"," * - `hidden` Allow transfer of hidden files. defaults to false"," * - `redirect` Redirect to trailing \"/\" when the pathname is a dir. defaults to true"," *"," * @param {String} root"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function static(root, options){"," options = options || {};",""," // root required"," if (!root) throw new Error('static() root path required');",""," // default redirect"," var redirect = false !== options.redirect;",""," return function static(req, res, next) {"," if ('GET' != req.method &amp;&amp; 'HEAD' != req.method) return next();"," var path = parse(req).pathname;"," var pause = utils.pause(req);",""," function resume() {"," next();"," pause.resume();"," }",""," function directory() {"," if (!redirect) return resume();"," var pathname = url.parse(req.originalUrl).pathname;"," res.statusCode = 301;"," res.setHeader('Location', pathname + '/');"," res.end('Redirecting to ' + utils.escape(pathname) + '/');"," }",""," function error(err) {"," if (404 == err.status) return resume();"," next(err);"," }",""," send(req, path)"," .maxage(options.maxAge || 0)"," .root(root)"," .hidden(options.hidden)"," .on('error', error)"," .on('directory', directory)"," .pipe(res);"," };","};","","/**"," * Expose mime module."," * "," * If you wish to extend the mime table use this"," * reference to the \"mime\" module in the npm registry."," */","","exports.mime = send.mime;"];

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,66 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/timeout.js']) {
_$jscoverage['middleware/timeout.js'] = [];
_$jscoverage['middleware/timeout.js'][12] = 0;
_$jscoverage['middleware/timeout.js'][30] = 0;
_$jscoverage['middleware/timeout.js'][31] = 0;
_$jscoverage['middleware/timeout.js'][33] = 0;
_$jscoverage['middleware/timeout.js'][34] = 0;
_$jscoverage['middleware/timeout.js'][35] = 0;
_$jscoverage['middleware/timeout.js'][38] = 0;
_$jscoverage['middleware/timeout.js'][39] = 0;
_$jscoverage['middleware/timeout.js'][40] = 0;
_$jscoverage['middleware/timeout.js'][41] = 0;
_$jscoverage['middleware/timeout.js'][42] = 0;
_$jscoverage['middleware/timeout.js'][43] = 0;
_$jscoverage['middleware/timeout.js'][46] = 0;
_$jscoverage['middleware/timeout.js'][47] = 0;
_$jscoverage['middleware/timeout.js'][50] = 0;
_$jscoverage['middleware/timeout.js'][51] = 0;
_$jscoverage['middleware/timeout.js'][54] = 0;
}
_$jscoverage['middleware/timeout.js'][12]++;
var debug = require("debug")("connect:timeout");
_$jscoverage['middleware/timeout.js'][30]++;
module.exports = (function timeout(ms) {
_$jscoverage['middleware/timeout.js'][31]++;
ms = ms || 5000;
_$jscoverage['middleware/timeout.js'][33]++;
return (function (req, res, next) {
_$jscoverage['middleware/timeout.js'][34]++;
var id = setTimeout((function () {
_$jscoverage['middleware/timeout.js'][35]++;
req.emit("timeout", ms);
}), ms);
_$jscoverage['middleware/timeout.js'][38]++;
req.on("timeout", (function () {
_$jscoverage['middleware/timeout.js'][39]++;
if (req.headerSent) {
_$jscoverage['middleware/timeout.js'][39]++;
return debug("response started, cannot timeout");
}
_$jscoverage['middleware/timeout.js'][40]++;
var err = new Error("Request timeout");
_$jscoverage['middleware/timeout.js'][41]++;
err.timeout = ms;
_$jscoverage['middleware/timeout.js'][42]++;
err.status = 408;
_$jscoverage['middleware/timeout.js'][43]++;
next(err);
}));
_$jscoverage['middleware/timeout.js'][46]++;
req.clearTimeout = (function () {
_$jscoverage['middleware/timeout.js'][47]++;
clearTimeout(id);
});
_$jscoverage['middleware/timeout.js'][50]++;
res.on("header", (function () {
_$jscoverage['middleware/timeout.js'][51]++;
clearTimeout(id);
}));
_$jscoverage['middleware/timeout.js'][54]++;
next();
});
});
_$jscoverage['middleware/timeout.js'].source = ["","/*!"," * Connect - timeout"," * Ported from https://github.com/LearnBoost/connect-timeout"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var debug = require('debug')('connect:timeout');","","/**"," * Timeout:"," *"," * Times out the request in `ms`, defaulting to `5000`. The"," * method `req.clearTimeout()` is added to revert this behaviour"," * programmatically within your application's middleware, routes, etc."," *"," * The timeout error is passed to `next()` so that you may customize"," * the response behaviour. This error has the `.timeout` property as"," * well as `.status == 408`."," *"," * @param {Number} ms"," * @return {Function}"," * @api public"," */","","module.exports = function timeout(ms) {"," ms = ms || 5000;",""," return function(req, res, next) {"," var id = setTimeout(function(){"," req.emit('timeout', ms);"," }, ms);",""," req.on('timeout', function(){"," if (req.headerSent) return debug('response started, cannot timeout');"," var err = new Error('Request timeout');"," err.timeout = ms;"," err.status = 408;"," next(err);"," });",""," req.clearTimeout = function(){"," clearTimeout(id);"," };",""," res.on('header', function(){"," clearTimeout(id);"," });",""," next();"," };","};"];

View File

@@ -0,0 +1,98 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/urlencoded.js']) {
_$jscoverage['middleware/urlencoded.js'] = [];
_$jscoverage['middleware/urlencoded.js'][13] = 0;
_$jscoverage['middleware/urlencoded.js'][21] = 0;
_$jscoverage['middleware/urlencoded.js'][22] = 0;
_$jscoverage['middleware/urlencoded.js'][40] = 0;
_$jscoverage['middleware/urlencoded.js'][41] = 0;
_$jscoverage['middleware/urlencoded.js'][43] = 0;
_$jscoverage['middleware/urlencoded.js'][47] = 0;
_$jscoverage['middleware/urlencoded.js'][48] = 0;
_$jscoverage['middleware/urlencoded.js'][49] = 0;
_$jscoverage['middleware/urlencoded.js'][51] = 0;
_$jscoverage['middleware/urlencoded.js'][54] = 0;
_$jscoverage['middleware/urlencoded.js'][57] = 0;
_$jscoverage['middleware/urlencoded.js'][60] = 0;
_$jscoverage['middleware/urlencoded.js'][61] = 0;
_$jscoverage['middleware/urlencoded.js'][62] = 0;
_$jscoverage['middleware/urlencoded.js'][63] = 0;
_$jscoverage['middleware/urlencoded.js'][64] = 0;
_$jscoverage['middleware/urlencoded.js'][65] = 0;
_$jscoverage['middleware/urlencoded.js'][66] = 0;
_$jscoverage['middleware/urlencoded.js'][67] = 0;
_$jscoverage['middleware/urlencoded.js'][70] = 0;
_$jscoverage['middleware/urlencoded.js'][72] = 0;
_$jscoverage['middleware/urlencoded.js'][73] = 0;
}
_$jscoverage['middleware/urlencoded.js'][13]++;
var utils = require("../utils"), _limit = require("./limit"), qs = require("qs");
_$jscoverage['middleware/urlencoded.js'][21]++;
function noop(req, res, next) {
_$jscoverage['middleware/urlencoded.js'][22]++;
next();
}
_$jscoverage['middleware/urlencoded.js'][40]++;
exports = module.exports = (function (options) {
_$jscoverage['middleware/urlencoded.js'][41]++;
options = options || {};
_$jscoverage['middleware/urlencoded.js'][43]++;
var limit = options.limit? _limit(options.limit): noop;
_$jscoverage['middleware/urlencoded.js'][47]++;
return (function urlencoded(req, res, next) {
_$jscoverage['middleware/urlencoded.js'][48]++;
if (req._body) {
_$jscoverage['middleware/urlencoded.js'][48]++;
return next();
}
_$jscoverage['middleware/urlencoded.js'][49]++;
req.body = req.body || {};
_$jscoverage['middleware/urlencoded.js'][51]++;
if (! utils.hasBody(req)) {
_$jscoverage['middleware/urlencoded.js'][51]++;
return next();
}
_$jscoverage['middleware/urlencoded.js'][54]++;
if ("application/x-www-form-urlencoded" != utils.mime(req)) {
_$jscoverage['middleware/urlencoded.js'][54]++;
return next();
}
_$jscoverage['middleware/urlencoded.js'][57]++;
req._body = true;
_$jscoverage['middleware/urlencoded.js'][60]++;
limit(req, res, (function (err) {
_$jscoverage['middleware/urlencoded.js'][61]++;
if (err) {
_$jscoverage['middleware/urlencoded.js'][61]++;
return next(err);
}
_$jscoverage['middleware/urlencoded.js'][62]++;
var buf = "";
_$jscoverage['middleware/urlencoded.js'][63]++;
req.setEncoding("utf8");
_$jscoverage['middleware/urlencoded.js'][64]++;
req.on("data", (function (chunk) {
_$jscoverage['middleware/urlencoded.js'][64]++;
buf += chunk;
}));
_$jscoverage['middleware/urlencoded.js'][65]++;
req.on("end", (function () {
_$jscoverage['middleware/urlencoded.js'][66]++;
try {
_$jscoverage['middleware/urlencoded.js'][67]++;
req.body = buf.length? qs.parse(buf, options): {};
_$jscoverage['middleware/urlencoded.js'][70]++;
next();
}
catch (err) {
_$jscoverage['middleware/urlencoded.js'][72]++;
err.body = buf;
_$jscoverage['middleware/urlencoded.js'][73]++;
next(err);
}
}));
}));
});
});
_$jscoverage['middleware/urlencoded.js'].source = ["","/*!"," * Connect - urlencoded"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils')"," , _limit = require('./limit')"," , qs = require('qs');","","/**"," * noop middleware."," */","","function noop(req, res, next) {"," next();","}","","/**"," * Urlencoded:"," * "," * Parse x-ww-form-urlencoded request bodies,"," * providing the parsed object as `req.body`."," *"," * Options:"," *"," * - `limit` byte limit disabled by default"," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function(options){"," options = options || {};",""," var limit = options.limit"," ? _limit(options.limit)"," : noop;",""," return function urlencoded(req, res, next) {"," if (req._body) return next();"," req.body = req.body || {};",""," if (!utils.hasBody(req)) return next();",""," // check Content-Type"," if ('application/x-www-form-urlencoded' != utils.mime(req)) return next();",""," // flag as parsed"," req._body = true;",""," // parse"," limit(req, res, function(err){"," if (err) return next(err);"," var buf = '';"," req.setEncoding('utf8');"," req.on('data', function(chunk){ buf += chunk });"," req.on('end', function(){"," try {"," req.body = buf.length"," ? qs.parse(buf, options)"," : {};"," next();"," } catch (err){"," err.body = buf;"," next(err);"," }"," });"," });"," }","};"];

View File

@@ -0,0 +1,59 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['middleware/vhost.js']) {
_$jscoverage['middleware/vhost.js'] = [];
_$jscoverage['middleware/vhost.js'][28] = 0;
_$jscoverage['middleware/vhost.js'][29] = 0;
_$jscoverage['middleware/vhost.js'][30] = 0;
_$jscoverage['middleware/vhost.js'][31] = 0;
_$jscoverage['middleware/vhost.js'][32] = 0;
_$jscoverage['middleware/vhost.js'][33] = 0;
_$jscoverage['middleware/vhost.js'][34] = 0;
_$jscoverage['middleware/vhost.js'][35] = 0;
_$jscoverage['middleware/vhost.js'][36] = 0;
_$jscoverage['middleware/vhost.js'][37] = 0;
_$jscoverage['middleware/vhost.js'][38] = 0;
}
_$jscoverage['middleware/vhost.js'][28]++;
module.exports = (function vhost(hostname, server) {
_$jscoverage['middleware/vhost.js'][29]++;
if (! hostname) {
_$jscoverage['middleware/vhost.js'][29]++;
throw new Error("vhost hostname required");
}
_$jscoverage['middleware/vhost.js'][30]++;
if (! server) {
_$jscoverage['middleware/vhost.js'][30]++;
throw new Error("vhost server required");
}
_$jscoverage['middleware/vhost.js'][31]++;
var regexp = new RegExp("^" + hostname.replace(/[*]/g, "(.*?)") + "$", "i");
_$jscoverage['middleware/vhost.js'][32]++;
if (server.onvhost) {
_$jscoverage['middleware/vhost.js'][32]++;
server.onvhost(hostname);
}
_$jscoverage['middleware/vhost.js'][33]++;
return (function vhost(req, res, next) {
_$jscoverage['middleware/vhost.js'][34]++;
if (! req.headers.host) {
_$jscoverage['middleware/vhost.js'][34]++;
return next();
}
_$jscoverage['middleware/vhost.js'][35]++;
var host = req.headers.host.split(":")[0];
_$jscoverage['middleware/vhost.js'][36]++;
if (! regexp.test(host)) {
_$jscoverage['middleware/vhost.js'][36]++;
return next();
}
_$jscoverage['middleware/vhost.js'][37]++;
if ("function" == typeof server) {
_$jscoverage['middleware/vhost.js'][37]++;
return server(req, res, next);
}
_$jscoverage['middleware/vhost.js'][38]++;
server.emit("request", req, res);
});
});
_$jscoverage['middleware/vhost.js'].source = ["","/*!"," * Connect - vhost"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Vhost:"," * "," * Setup vhost for the given `hostname` and `server`."," *"," * connect()"," * .use(connect.vhost('foo.com', fooApp))"," * .use(connect.vhost('bar.com', barApp))"," * .use(connect.vhost('*.com', mainApp))"," *"," * The `server` may be a Connect server or"," * a regular Node `http.Server`. "," *"," * @param {String} hostname"," * @param {Server} server"," * @return {Function}"," * @api public"," */","","module.exports = function vhost(hostname, server){"," if (!hostname) throw new Error('vhost hostname required');"," if (!server) throw new Error('vhost server required');"," var regexp = new RegExp('^' + hostname.replace(/[*]/g, '(.*?)') + '$', 'i');"," if (server.onvhost) server.onvhost(hostname);"," return function vhost(req, res, next){"," if (!req.headers.host) return next();"," var host = req.headers.host.split(':')[0];"," if (!regexp.test(host)) return next();"," if ('function' == typeof server) return server(req, res, next);"," server.emit('request', req, res);"," };","};"];

View File

@@ -0,0 +1,85 @@
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['patch.js']) {
_$jscoverage['patch.js'] = [];
_$jscoverage['patch.js'][12] = 0;
_$jscoverage['patch.js'][20] = 0;
_$jscoverage['patch.js'][30] = 0;
_$jscoverage['patch.js'][31] = 0;
_$jscoverage['patch.js'][43] = 0;
_$jscoverage['patch.js'][44] = 0;
_$jscoverage['patch.js'][48] = 0;
_$jscoverage['patch.js'][49] = 0;
_$jscoverage['patch.js'][50] = 0;
_$jscoverage['patch.js'][55] = 0;
_$jscoverage['patch.js'][56] = 0;
_$jscoverage['patch.js'][59] = 0;
_$jscoverage['patch.js'][66] = 0;
_$jscoverage['patch.js'][67] = 0;
_$jscoverage['patch.js'][68] = 0;
_$jscoverage['patch.js'][69] = 0;
_$jscoverage['patch.js'][72] = 0;
_$jscoverage['patch.js'][73] = 0;
_$jscoverage['patch.js'][74] = 0;
_$jscoverage['patch.js'][75] = 0;
_$jscoverage['patch.js'][78] = 0;
}
_$jscoverage['patch.js'][12]++;
var http = require("http"), res = http.ServerResponse.prototype, setHeader = res.setHeader, _renderHeaders = res._renderHeaders, writeHead = res.writeHead;
_$jscoverage['patch.js'][20]++;
if (! res._hasConnectPatch) {
_$jscoverage['patch.js'][30]++;
res.__defineGetter__("headerSent", (function () {
_$jscoverage['patch.js'][31]++;
return this._header;
}));
_$jscoverage['patch.js'][43]++;
res.setHeader = (function (field, val) {
_$jscoverage['patch.js'][44]++;
var key = field.toLowerCase(), prev;
_$jscoverage['patch.js'][48]++;
if (this._headers && "set-cookie" == key) {
_$jscoverage['patch.js'][49]++;
if (prev = this.getHeader(field)) {
_$jscoverage['patch.js'][50]++;
val = Array.isArray(prev)? prev.concat(val): [prev, val];
}
}
else {
_$jscoverage['patch.js'][55]++;
if ("content-type" == key && this.charset) {
_$jscoverage['patch.js'][56]++;
val += "; charset=" + this.charset;
}
}
_$jscoverage['patch.js'][59]++;
return setHeader.call(this, field, val);
});
_$jscoverage['patch.js'][66]++;
res._renderHeaders = (function () {
_$jscoverage['patch.js'][67]++;
if (! this._emittedHeader) {
_$jscoverage['patch.js'][67]++;
this.emit("header");
}
_$jscoverage['patch.js'][68]++;
this._emittedHeader = true;
_$jscoverage['patch.js'][69]++;
return _renderHeaders.call(this);
});
_$jscoverage['patch.js'][72]++;
res.writeHead = (function () {
_$jscoverage['patch.js'][73]++;
if (! this._emittedHeader) {
_$jscoverage['patch.js'][73]++;
this.emit("header");
}
_$jscoverage['patch.js'][74]++;
this._emittedHeader = true;
_$jscoverage['patch.js'][75]++;
return writeHead.apply(this, arguments);
});
_$jscoverage['patch.js'][78]++;
res._hasConnectPatch = true;
}
_$jscoverage['patch.js'].source = ["","/*!"," * Connect"," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var http = require('http')"," , res = http.ServerResponse.prototype"," , setHeader = res.setHeader"," , _renderHeaders = res._renderHeaders"," , writeHead = res.writeHead;","","// apply only once","","if (!res._hasConnectPatch) {",""," /**"," * Provide a public \"header sent\" flag"," * until node does."," *"," * @return {Boolean}"," * @api public"," */",""," res.__defineGetter__('headerSent', function(){"," return this._header;"," });",""," /**"," * 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 (this._headers &amp;&amp; 'set-cookie' == key) {"," if (prev = this.getHeader(field)) {"," val = Array.isArray(prev)"," ? prev.concat(val)"," : [prev, val];"," }"," // charset"," } else if ('content-type' == key &amp;&amp; this.charset) {"," val += '; charset=' + this.charset;"," }",""," return setHeader.call(this, field, val);"," };",""," /**"," * Proxy to emit \"header\" event."," */",""," res._renderHeaders = function(){"," if (!this._emittedHeader) this.emit('header');"," this._emittedHeader = true;"," return _renderHeaders.call(this);"," };",""," res.writeHead = function(){"," if (!this._emittedHeader) this.emit('header');"," this._emittedHeader = true;"," return writeHead.apply(this, arguments);"," };",""," res._hasConnectPatch = true;","}"];

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,75 @@
<html>
<head>
<title>listing directory {directory}</title>
<style>{style}</style>
<script>
function $(id){
var el = 'string' == typeof id
? document.getElementById(id)
: id;
el.on = function(event, fn){
if ('content loaded' == event) event = 'DOMContentLoaded';
el.addEventListener(event, fn, false);
};
el.all = function(selector){
return $(el.querySelectorAll(selector));
};
el.each = function(fn){
for (var i = 0, len = el.length; i < len; ++i) {
fn($(el[i]), i);
}
};
el.getClasses = function(){
return this.getAttribute('class').split(/\s+/);
};
el.addClass = function(name){
var classes = this.getAttribute('class');
el.setAttribute('class', classes
? classes + ' ' + name
: name);
};
el.removeClass = function(name){
var classes = this.getClasses().filter(function(curr){
return curr != name;
});
this.setAttribute('class', classes);
};
return el;
}
function search() {
var str = $('search').value
, links = $('files').all('a');
links.each(function(link){
var text = link.textContent;
if ('..' == text) return;
if (str.length && ~text.indexOf(str)) {
link.addClass('highlight');
} else {
link.removeClass('highlight');
}
});
}
$(window).on('content loaded', function(){
$('search').on('keyup', search);
});
</script>
</head>
<body class="directory">
<input id="search" type="text" placeholder="Search" autocomplete="off" />
<div id="wrapper">
<h1>{linked-path}</h1>
{files}
</div>
</body>
</html>

View File

@@ -0,0 +1,13 @@
<html>
<head>
<title>{error}</title>
<style>{style}</style>
</head>
<body>
<div id="wrapper">
<h1>{title}</h1>
<h2><em>{statusCode}</em> {error}</h2>
<ul id="stacktrace">{stack}</ul>
</div>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 635 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 739 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 794 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 818 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 663 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 740 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 807 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 793 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 817 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 879 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 833 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 779 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 621 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 801 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 839 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 830 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 813 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 703 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 641 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 858 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 774 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 294 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 591 B

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