Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

first commit

  • Loading branch information...
commit 0256b56edd98d3daef573cdc26e6759c291d23a8 0 parents
@fabrik42 fabrik42 authored
Showing with 7,148 additions and 0 deletions.
  1. 0  README.md
  2. +1 −0  index.js
  3. +84 −0 lib/pusher.js
  4. +1 −0  node_modules/.bin/nodeunit
  5. +3 −0  node_modules/nodeunit/.gitignore
  6. +3 −0  node_modules/nodeunit/.npmignore
  7. +60 −0 node_modules/nodeunit/CONTRIBUTORS.md
  8. +19 −0 node_modules/nodeunit/LICENSE
  9. +126 −0 node_modules/nodeunit/Makefile
  10. +433 −0 node_modules/nodeunit/README.md
  11. +108 −0 node_modules/nodeunit/bin/nodeunit
  12. +10 −0 node_modules/nodeunit/bin/nodeunit.json
  13. +623 −0 node_modules/nodeunit/deps/async.js
  14. +125 −0 node_modules/nodeunit/deps/ejs.js
  15. +483 −0 node_modules/nodeunit/deps/json2.js
  16. +60 −0 node_modules/nodeunit/doc/nodeunit.md
  17. +1,757 −0 node_modules/nodeunit/examples/browser/nodeunit.js
  18. +12 −0 node_modules/nodeunit/examples/browser/suite1.js
  19. +13 −0 node_modules/nodeunit/examples/browser/suite2.js
  20. +16 −0 node_modules/nodeunit/examples/browser/test.html
  21. BIN  node_modules/nodeunit/img/example_fail.png
  22. BIN  node_modules/nodeunit/img/example_pass.png
  23. +3 −0  node_modules/nodeunit/index.js
  24. +316 −0 node_modules/nodeunit/lib/assert.js
  25. +236 −0 node_modules/nodeunit/lib/core.js
  26. +80 −0 node_modules/nodeunit/lib/nodeunit.js
  27. +119 −0 node_modules/nodeunit/lib/reporters/browser.js
  28. +131 −0 node_modules/nodeunit/lib/reporters/default.js
  29. +112 −0 node_modules/nodeunit/lib/reporters/html.js
  30. +9 −0 node_modules/nodeunit/lib/reporters/index.js
  31. +186 −0 node_modules/nodeunit/lib/reporters/junit.js
  32. +117 −0 node_modules/nodeunit/lib/reporters/minimal.js
  33. +110 −0 node_modules/nodeunit/lib/reporters/skip_passed.js
  34. +50 −0 node_modules/nodeunit/lib/track.js
  35. +187 −0 node_modules/nodeunit/lib/types.js
  36. +209 −0 node_modules/nodeunit/lib/utils.js
  37. +95 −0 node_modules/nodeunit/man1/nodeunit.1
  38. +4 −0 node_modules/nodeunit/nodelint.cfg
  39. +53 −0 node_modules/nodeunit/package.json
  40. +19 −0 node_modules/nodeunit/share/junit.xml.ejs
  41. +11 −0 node_modules/nodeunit/share/license.js
  42. +70 −0 node_modules/nodeunit/share/nodeunit.css
  43. +4 −0 node_modules/nodeunit/test/fixtures/coffee/mock_coffee_module.coffee
  44. +1 −0  node_modules/nodeunit/test/fixtures/dir/mock_module3.js
  45. +1 −0  node_modules/nodeunit/test/fixtures/dir/mock_module4.js
  46. +1 −0  node_modules/nodeunit/test/fixtures/mock_module1.js
  47. +1 −0  node_modules/nodeunit/test/fixtures/mock_module2.js
  48. +3 −0  node_modules/nodeunit/test/fixtures/raw_jscode1.js
  49. +3 −0  node_modules/nodeunit/test/fixtures/raw_jscode2.js
  50. +1 −0  node_modules/nodeunit/test/fixtures/raw_jscode3.js
  51. +219 −0 node_modules/nodeunit/test/test-base.js
  52. +114 −0 node_modules/nodeunit/test/test-failing-callbacks.js
  53. +55 −0 node_modules/nodeunit/test/test-httputil.js
  54. +214 −0 node_modules/nodeunit/test/test-runfiles.js
  55. +125 −0 node_modules/nodeunit/test/test-runmodule.js
  56. +46 −0 node_modules/nodeunit/test/test-runtest.js
  57. +31 −0 node_modules/nodeunit/test/test-sandbox.js
  58. +234 −0 node_modules/nodeunit/test/test-testcase.js
  59. +26 −0 node_modules/nodeunit/test/test.html
  60. +15 −0 package.json
0  README.md
No changes.
1  index.js
@@ -0,0 +1 @@
+module.exports = require('./lib/pusher');
84 lib/pusher.js
@@ -0,0 +1,84 @@
+module.exports = (function(){
+ var crypto = require('crypto'),
+ http = require('http'),
+ sys = require('sys');
+
+ var Pusher = function(options) {
+ this.options = options;
+
+ return this;
+ }
+
+ Pusher.prototype.domain = 'api.pusherapp.com';
+
+ Pusher.prototype.channel = function(channel) {
+ if(typeof channel === 'undefined') return this.options.channel;
+ this.options.channel = channel;
+
+ return this;
+ }
+
+ Pusher.prototype.trigger = function(event, data, callback) {
+ this.event = event;
+ this.data = JSON.stringify(data);
+ this.send(callback);
+
+ return this;
+ }
+
+ Pusher.prototype.send = function(callback) {
+ var client = http.createClient(80, this.domain);
+ var request = client.request('POST', this.path(), {
+ 'host': this.domain,
+ 'Content-Type': 'application/json',
+ 'Content-Length': this.data.length
+ });
+
+ if(callback) {
+ client.addListener('error', function(error) {
+ callback(error, request, null);
+ });
+
+ request.addListener('response', function(response) {
+ callback(null, request, response);
+ });
+ }
+
+ request.write(this.data);
+ request.end();
+
+ return request;
+ }
+
+ Pusher.prototype.path = function() {
+ return this.uri() + '?' + this.queryString() + '&auth_signature=' + this.signature();
+ }
+
+ Pusher.prototype.uri = function() {
+ return '/apps/' + this.options.appId + '/channels/' + this.options.channel + '/events';
+ }
+
+ Pusher.prototype.queryString = function() {
+ var timestamp = parseInt(new Date().getTime() / 1000);
+
+ return [
+ 'auth_key=', this.options.appKey,
+ '&auth_timestamp=', timestamp,
+ '&auth_version=', '1.0',
+ '&body_md5=', this.hash(),
+ '&name=', this.event
+ ].join('');
+ }
+
+ Pusher.prototype.hash = function() {
+ return crypto.createHash('md5').update(this.data).digest("hex");
+ }
+
+ Pusher.prototype.signature = function(uri, queryString) {
+ var signData = ['POST', this.uri(), this.queryString()].join('\n');
+
+ return crypto.createHmac('sha256', this.options.secret).update(signData).digest('hex');
+ }
+
+ return Pusher;
+})();
1  node_modules/.bin/nodeunit
3  node_modules/nodeunit/.gitignore
@@ -0,0 +1,3 @@
+dist
+stamp-build
+*~
3  node_modules/nodeunit/.npmignore
@@ -0,0 +1,3 @@
+dist
+stamp-build
+test/fixtures/dir2
60 node_modules/nodeunit/CONTRIBUTORS.md
@@ -0,0 +1,60 @@
+Nodeunit contributors (sorted alphabeticaly)
+============================================
+
+* **[Alex Gorbatchev](https://github.com/alexgorbatchev)**
+
+ * Deeper default object inspection
+ * Timeout to ensure flushing of console output (default reporter)
+
+* **[Alex Wolfe](https://github.com/alexkwolfe)**
+
+ * HTML test reporter
+
+* **[Caolan McMahon](https://github.com/caolan)**
+
+ * Author and maintainer
+ * Most features develpopment
+
+* **[Carl Fürstenberg](https://github.com/azatoth)**
+
+ * Debian-friendly Makefile, supports both 'node' and 'nodejs' executables
+ * Sandbox utility
+ * Minimal test reporter
+
+* **[Gerad Suyderhoud](https://github.com/gerad)**
+
+ * First comand-line tool
+
+* **[Kadir Pekel](https://github.com/coffeemate)**
+
+ * Improvements to default test reporter
+ * HTTP test utility
+
+* **[Matthias Lübken](https://github.com/luebken)**
+
+ * Utility functions for tracking incomplete tests on exit
+
+* **[Oleg Efimov](https://github.com/Sannis)**
+
+ * Adding 'make lint' and fixing nodelint errors
+ * Option parsing, --help text and config file support
+ * Reporters option for command-line tool
+
+* **[Orlando Vazquez](https://github.com/orlandov)**
+
+ * Added jUnit XML reporter
+
+* **[Ryan Dahl](https://github.com/ry)**
+
+ * Add package.json
+
+* **[Sam Stephenson](https://github.com/sstephenson)**
+
+ * Coffee-script support
+
+* **[Thomas Mayfield](https://github.com/thegreatape)**
+
+ * Async setUp and tearDown support for testCase
+
+**[Full contributors list](https://github.com/caolan/nodeunit/contributors).**
+
19 node_modules/nodeunit/LICENSE
@@ -0,0 +1,19 @@
+Copyright (c) 2010 Caolan McMahon
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
126 node_modules/nodeunit/Makefile
@@ -0,0 +1,126 @@
+PACKAGE = nodeunit
+NODEJS = $(if $(shell test -f /usr/bin/nodejs && echo "true"),nodejs,node)
+
+PREFIX ?= /usr/local
+BINDIR ?= $(PREFIX)/bin
+DATADIR ?= $(PREFIX)/share
+MANDIR ?= $(PREFIX)/share/man
+LIBDIR ?= $(PREFIX)/lib
+NODEJSLIBDIR ?= $(LIBDIR)/$(NODEJS)
+
+BUILDDIR = dist
+
+DOCS = $(shell find doc -name '*.md' \
+ |sed 's|.md|.1|g' \
+ |sed 's|doc/|man1/|g' \
+ )
+
+
+$(shell if [ ! -d $(BUILDDIR) ]; then mkdir $(BUILDDIR); fi)
+
+all: build doc
+
+browser:
+ # super hacky build script for browser version!
+ mkdir -p $(BUILDDIR)/browser
+ rm -rf $(BUILDDIR)/browser/*
+ # build browser version of nodeunit.js
+ cat share/license.js >> $(BUILDDIR)/browser/nodeunit.js
+ echo "nodeunit = (function(){" >> $(BUILDDIR)/browser/nodeunit.js
+ cat deps/json2.js >> $(BUILDDIR)/browser/nodeunit.js
+ # make assert global
+ echo "var assert = this.assert = {};" >> $(BUILDDIR)/browser/nodeunit.js
+ echo "var types = {};" >> $(BUILDDIR)/browser/nodeunit.js
+ echo "var core = {};" >> $(BUILDDIR)/browser/nodeunit.js
+ echo "var nodeunit = {};" >> $(BUILDDIR)/browser/nodeunit.js
+ echo "var reporter = {};" >> $(BUILDDIR)/browser/nodeunit.js
+ cat deps/async.js >> $(BUILDDIR)/browser/nodeunit.js
+ echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js
+ cat lib/assert.js >> $(BUILDDIR)/browser/nodeunit.js
+ echo "})(assert);" >> $(BUILDDIR)/browser/nodeunit.js
+ echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js
+ cat lib/types.js >> $(BUILDDIR)/browser/nodeunit.js
+ echo "})(types);" >> $(BUILDDIR)/browser/nodeunit.js
+ echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js
+ cat lib/core.js >> $(BUILDDIR)/browser/nodeunit.js
+ echo "})(core);" >> $(BUILDDIR)/browser/nodeunit.js
+ echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js
+ cat lib/reporters/browser.js >> $(BUILDDIR)/browser/nodeunit.js
+ echo "})(reporter);" >> $(BUILDDIR)/browser/nodeunit.js
+ echo "nodeunit = core;" >> $(BUILDDIR)/browser/nodeunit.js
+ echo "nodeunit.assert = assert;" >> $(BUILDDIR)/browser/nodeunit.js
+ echo "nodeunit.reporter = reporter;" >> $(BUILDDIR)/browser/nodeunit.js
+ echo "nodeunit.run = reporter.run;" >> $(BUILDDIR)/browser/nodeunit.js
+ echo "return nodeunit; })();" >> $(BUILDDIR)/browser/nodeunit.js
+ sed -i "/\@REMOVE_LINE_FOR_BROWSER/d" $(BUILDDIR)/browser/nodeunit.js
+ # copy nodeunit.css
+ cp share/nodeunit.css $(BUILDDIR)/browser/nodeunit.css
+ # create nodeunit.min.js
+ uglifyjs $(BUILDDIR)/browser/nodeunit.js > $(BUILDDIR)/browser/nodeunit.min.js
+ # create test scripts
+ mkdir -p $(BUILDDIR)/browser/test
+ cp test/test.html $(BUILDDIR)/browser/test/test.html
+ # test-base.js
+ echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-base.js
+ cat test/test-base.js >> $(BUILDDIR)/browser/test/test-base.js
+ echo "})(this.test_base = {});" >> $(BUILDDIR)/browser/test/test-base.js
+ sed -i "/\@REMOVE_LINE_FOR_BROWSER/d" $(BUILDDIR)/browser/test/test-base.js
+ # test-runmodule.js
+ echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-runmodule.js
+ cat test/test-runmodule.js >> $(BUILDDIR)/browser/test/test-runmodule.js
+ echo "})(this.test_runmodule = {});" >> $(BUILDDIR)/browser/test/test-runmodule.js
+ sed -i "/\@REMOVE_LINE_FOR_BROWSER/d" $(BUILDDIR)/browser/test/test-runmodule.js
+ # test-runtest.js
+ echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-runtest.js
+ cat test/test-runtest.js >> $(BUILDDIR)/browser/test/test-runtest.js
+ echo "})(this.test_runtest = {});" >> $(BUILDDIR)/browser/test/test-runtest.js
+ sed -i "/\@REMOVE_LINE_FOR_BROWSER/d" $(BUILDDIR)/browser/test/test-runtest.js
+ # test-testcase.js
+ echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-testcase.js
+ cat test/test-testcase.js >> $(BUILDDIR)/browser/test/test-testcase.js
+ echo "})(this.test_testcase = {});" >> $(BUILDDIR)/browser/test/test-testcase.js
+ sed -i "/\@REMOVE_LINE_FOR_BROWSER/d" $(BUILDDIR)/browser/test/test-testcase.js
+ # copy nodeunit.js to dist/browser/test to make it easier for me to host and
+ # run on windows VMs with IE
+ cp $(BUILDDIR)/browser/nodeunit.js $(BUILDDIR)/browser/test/nodeunit.js
+ cp $(BUILDDIR)/browser/nodeunit.css $(BUILDDIR)/browser/test/nodeunit.css
+
+build: stamp-build
+
+stamp-build: $(wildcard deps/* lib/*.js)
+ touch $@;
+ mkdir -p $(BUILDDIR)/nodeunit
+ cp -R bin deps index.js lib package.json $(BUILDDIR)/nodeunit
+ printf '#!/bin/sh\n$(NODEJS) $(NODEJSLIBDIR)/$(PACKAGE)/bin/nodeunit $$@' > $(BUILDDIR)/nodeunit.sh
+
+test:
+ $(NODEJS) ./bin/nodeunit test
+
+install: build
+ install -d $(NODEJSLIBDIR)
+ cp -a $(BUILDDIR)/nodeunit $(NODEJSLIBDIR)
+ install -m 0755 $(BUILDDIR)/nodeunit.sh $(BINDIR)/nodeunit
+ install -d $(MANDIR)/man1/
+ cp -a man1/nodeunit.1 $(MANDIR)/man1/
+
+uninstall:
+ rm -rf $(NODEJSLIBDIR)/nodeunit $(NODEJSLIBDIR)/nodeunit.js $(BINDIR)/nodeunit
+ rm -rf $(MANDIR)/man1/nodeunit.1
+
+clean:
+ rm -rf $(BUILDDIR) stamp-build
+
+lint:
+ nodelint --config nodelint.cfg ./index.js ./bin/nodeunit ./bin/nodeunit.json ./lib/*.js ./lib/reporters/*.js ./test/*.js
+
+doc: man1 $(DOCS)
+ @true
+
+man1:
+ @if ! test -d man1 ; then mkdir -p man1 ; fi
+
+# use `npm install ronn` for this to work.
+man1/%.1: doc/%.md
+ ronn --roff $< > $@
+
+.PHONY: browser test install uninstall build all
433 node_modules/nodeunit/README.md
@@ -0,0 +1,433 @@
+Nodeunit
+========
+
+Simple syntax, powerful tools. Nodeunit provides easy async unit testing for
+node.js and the browser.
+
+* Simple to use
+* Just export the tests from a module
+* Works with node.js and in the browser.
+* Helps you avoid common pitfalls when testing asynchronous code
+* Easy to add test cases with setUp and tearDown functions if you wish
+* Flexible reporters for custom output, built-in support for HTML and jUnit XML
+* Allows the use of mocks and stubs
+
+__Contributors__
+
+* [alexgorbatchev](https://github.com/alexgorbatchev)
+* [alexkwolfe](https://github.com/alexkwolfe)
+* [azatoth](https://github.com/azatoth)
+* [coffeemate](https://github.com/coffeemate)
+* [luebken](https://github.com/luebken)
+* [orlandov](https://github.com/orlandov)
+* [Sannis](https://github.com/Sannis)
+* [sstephenson](https://github.com/sstephenson)
+* [thegreatape](https://github.com/thegreatape)
+* and thanks to [cjohansen](https://github.com/cjohansen) for input and advice
+ on implementing setUp and tearDown functions. See
+ [cjohansen's fork](https://github.com/cjohansen/nodeunit).
+
+Also, check out gerad's [nodeunit-dsl](https://github.com/gerad/nodeunit-dsl)
+project, which implements a 'pretty dsl on top of nodeunit'.
+
+More contributor information can be found in the
+[CONTRIBUTORS.md](https://github.com/caolan/nodeunit/blob/master/CONTRIBUTORS.md)
+file.
+
+Usage
+-----
+
+Here is an example unit test module:
+
+ exports.testSomething = function(test){
+ test.expect(1);
+ test.ok(true, "this assertion should pass");
+ test.done();
+ };
+
+ exports.testSomethingElse = function(test){
+ test.ok(false, "this assertion should fail");
+ test.done();
+ };
+
+When run using the included test runner, this will output the following:
+
+<img src="https://github.com/caolan/nodeunit/raw/master/img/example_fail.png" />
+
+Installation
+------------
+
+There are two options for installing nodeunit:
+
+1. Clone / download nodeunit from [github](https://github.com/caolan/nodeunit),
+ then:
+
+ make && sudo make install
+
+2. Install via npm:
+
+ npm install nodeunit
+
+API Documentation
+-----------------
+
+Nodeunit uses the functions available in the node.js
+[assert module](http://nodejs.org/api.html#assert-280):
+
+* __ok(value, [message])__ - Tests if value is a true value.
+* __equal(actual, expected, [message])__ - Tests shallow, coercive equality
+ with the equal comparison operator ( == ).
+* __notEqual(actual, expected, [message])__ - Tests shallow, coercive
+ non-equality with the not equal comparison operator ( != ).
+* __deepEqual(actual, expected, [message])__ - Tests for deep equality.
+* __notDeepEqual(actual, expected, [message])__ - Tests for any deep
+ inequality.
+* __strictEqual(actual, expected, [message])__ - Tests strict equality, as
+ determined by the strict equality operator ( === )
+* __notStrictEqual(actual, expected, [message])__ - Tests strict non-equality,
+ as determined by the strict not equal operator ( !== )
+* __throws(block, [error], [message])__ - Expects block to throw an error.
+* __doesNotThrow(block, [error], [message])__ - Expects block not to throw an
+ error.
+* __ifError(value)__ - Tests if value is not a false value, throws if it is a
+ true value. Useful when testing the first argument, error in callbacks.
+
+Nodeunit also provides the following functions within tests:
+
+* __expect(amount)__ - Specify how many assertions are expected to run within a
+ test. Very useful for ensuring that all your callbacks and assertions are
+ run.
+* __done()__ - Finish the current test function, and move on to the next. ALL
+ tests should call this!
+
+Nodeunit aims to be simple and easy to learn. This is achieved through using
+existing structures (such as node.js modules) to maximum effect, and reducing
+the API where possible, to make it easier to digest.
+
+Tests are simply exported from a module, but they are still run in the order
+they are defined.
+
+__Note:__ Users of old nodeunit versions may remember using ok, equals and same
+in the style of qunit, instead of the assert functions above. These functions
+still exist for backwards compatibility, and are simply aliases to their assert
+module counterparts.
+
+
+Asynchronous Testing
+--------------------
+
+When testing asynchronous code, there are a number of sharp edges to watch out
+for. Thankfully, nodeunit is designed to help you avoid as many of these
+pitfalls as possible. For the most part, testing asynchronous code in nodeunit
+_just works_.
+
+
+### Tests run in series
+
+While running tests in parallel seems like a good idea for speeding up your
+test suite, in practice I've found it means writing much more complicated
+tests. Because of node's module cache, running tests in parallel means mocking
+and stubbing is pretty much impossible. One of the nicest things about testing
+in javascript is the ease of doing stubs:
+
+ var _readFile = fs.readFile;
+ fs.readFile = function(path, callback){
+ // its a stub!
+ };
+ // test function that uses fs.readFile
+
+ // we're done
+ fs.readFile = _readFile;
+
+You cannot do this when running tests in parallel. In order to keep testing as
+simple as possible, nodeunit avoids it. Thankfully, most unit-test suites run
+fast anyway.
+
+
+### Explicit ending of tests
+
+When testing async code its important that tests end at the correct point, not
+just after a given number of assertions. Otherwise your tests can run short,
+ending before all assertions have completed. Its important to detect too
+many assertions as well as too few. Combining explicit ending of tests with
+an expected number of assertions helps to avoid false test passes, so be sure
+to use the test.expect() method at the start of your test functions, and
+test.done() when finished.
+
+
+Groups, setUp and tearDown
+--------------------------
+
+Nodeunit allows the nesting of test functions:
+
+ exports.test1 = function (test) {
+ ...
+ }
+
+ exports.group = {
+ test2: function (test) {
+ ...
+ },
+ test3: function (test) {
+ ...
+ }
+ }
+
+This would be run as:
+
+ test1
+ group - test2
+ group - test3
+
+Using these groups its possible to add setUp and tearDown functions to your
+tests. Nodeunit has a utility function called testCase which allows you to
+define a setUp function, which is run before each test, and a tearDown
+function, which is run after each test calls test.done():
+
+ var testCase = require('nodeunit').testCase;
+
+ module.exports = testCase({
+ setUp: function (callback) {
+ this.foo = 'bar';
+ callback();
+ },
+ tearDown: function (callback) {
+ // clean up
+ callback();
+ },
+ test1: function (test) {
+ test.equals(this.foo, 'bar');
+ test.done();
+ }
+ });
+
+In this way, its possible to have multiple groups of tests in a module, each
+group with its own setUp and tearDown functions.
+
+
+Running Tests
+-------------
+
+Nodeunit comes with a basic command-line test runner, which can be installed
+using 'sudo make install'. Example usage:
+
+ nodeunit testmodule1.js testfolder [...]
+
+The default test reporter uses color output, because I think that's more fun :) I
+intend to add a no-color option in future. To give you a feeling of the fun you'll
+be having writing tests, lets fix the example at the start of the README:
+
+<img src="https://github.com/caolan/nodeunit/raw/master/img/example_pass.png" />
+
+Ahhh, Doesn't that feel better?
+
+When using the included test runner, it will exit using the failed number of
+assertions as the exit code. Exiting with 0 when all tests pass.
+
+
+### Command-line Options
+
+* __--reporter FILE__ - you can set the test reporter to a custom module or
+on of the modules in nodeunit/lib/reporters, when omitted, the default test runner
+is used.
+* __--list-reporters__ - list available build-in reporters.
+* __--config FILE__ - load config options from a JSON file, allows
+the customisation of color schemes for the default test reporter etc. See
+bin/nodeunit.json for current available options.
+* __--version__ or __-v__ - report nodeunit version
+* __--help__ - show nodeunit help
+
+
+Running tests in the browser
+----------------------------
+
+Nodeunit tests can also be run inside the browser. For example usage, see
+the examples/browser folder. The basic syntax is as follows:
+
+__test.html__
+
+ <html>
+ <head>
+ <title>Example Test Suite</title>
+ <link rel="stylesheet" href="nodeunit.css" type="text/css" />
+ <script src="nodeunit.js"></script>
+ <script src="suite1.js"></script>
+ <script src="suite2.js"></script>
+ </head>
+ <body>
+ <h1 id="nodeunit-header>Example Test Suite</h1>
+ <script>
+ nodeunit.run({
+ 'Suite One': suite1,
+ 'Suite Two': suite2
+ });
+ </script>
+ </body>
+ </html>
+
+Here, suite1 and suite2 are just object literals containing test functions or
+groups, as would be returned if you did require('test-suite') in node.js:
+
+__suite1.js__
+
+ this.suite1 = {
+ 'example test': function (test) {
+ test.ok(true, 'everything is ok');
+ test.done();
+ }
+ };
+
+If you wish to use a commonjs format for your test suites (using exports), it is
+up to you to define the commonjs tools for the browser. There are a number of
+alternatives and its important it fits with your existing code, which is
+why nodeunit does not currently provide this out of the box.
+
+In the example above, the tests will run when the page is loaded.
+
+The browser-version of nodeunit.js is created in dist/browser when you do, 'make
+browser'. You'll need [UglifyJS](https://github.com/mishoo/UglifyJS) installed in
+order for it to automatically create nodeunit.min.js.
+
+
+Adding nodeunit to Your Projects
+--------------------------------
+
+If you don't want people to have to install the nodeunit command-line tool,
+you'll want to create a script that runs the tests for your project with the
+correct require paths set up. Here's an example test script, with a deps
+directory containing the projects dependencies:
+
+ #!/usr/bin/env node
+ require.paths.unshift(__dirname + '/deps');
+
+ var reporter = require('nodeunit').reporters.default;
+ reporter.run(['test']);
+
+If you're using git, you might find it useful to include nodeunit as a
+submodule. Using submodules makes it easy for developers to download nodeunit
+and run your test suite, without cluttering up your repository with
+the source code. To add nodeunit as a git submodule do the following:
+
+ git submodule add git://github.com/caolan/nodeunit.git deps/nodeunit
+
+This will add nodeunit to the deps folder of your project. Now, when cloning
+the repository, nodeunit can be downloaded by doing the following:
+
+ git submodule init
+ git submodule update
+
+Let's update the test script above with a helpful hint on how to get nodeunit,
+if its missing:
+
+ #!/usr/bin/env node
+
+ require.paths.unshift(__dirname + '/deps');
+
+ try {
+ var reporter = require('nodeunit').reporters.default;
+ }
+ catch(e) {
+ var sys = require('sys');
+ sys.puts("Cannot find nodeunit module.");
+ sys.puts("You can download submodules for this project by doing:");
+ sys.puts("");
+ sys.puts(" git submodule init");
+ sys.puts(" git submodule update");
+ sys.puts("");
+ process.exit();
+ }
+
+ process.chdir(__dirname);
+ reporter.run(['test']);
+
+Now if someone attempts to run your test suite without nodeunit installed they
+will be prompted to download the submodules for your project.
+
+
+Built-in Test Reporters
+-----------------------
+
+* __default__ - The standard reporter seen in the nodeunit screenshots
+* __minimal__ - Pretty, minimal output, shows errors and progress only
+* __html__ - Outputs a HTML report to stdout
+* __junit__ - Creates jUnit compatible XML reports, which can be used with
+ continuous integration tools such as [Hudson](http://hudson-ci.org/).
+
+
+Writing a Test Reporter
+---------------------
+
+Nodeunit exports runTest(fn, options), runModule(mod, options) and
+runFiles(paths, options). You'll most likely want to run test suites from
+files, which can be done using the latter function. The _options_ argument can
+contain callbacks which run during testing. Nodeunit provides the following
+callbacks:
+
+* __moduleStart(name)__ - called before a module is tested
+* __moduleDone(name, assertions)__ - called once all test functions within the
+ module have completed (see assertions object reference below)
+ ALL tests within the module
+* __testStart(name)__ - called before a test function is run
+* __testDone(name, assertions)__ - called once a test function has completed
+ (by calling test.done())
+* __log(assertion)__ - called whenever an assertion is made (see assertion
+ object reference below)
+* __done(assertions)__ - called after all tests/modules are complete
+
+The __assertion__ object:
+
+* __passed()__ - did the assertion pass?
+* __failed()__ - did the assertion fail?
+* __error__ - the AssertionError if the assertion failed
+* __method__ - the nodeunit assertion method used (ok, same, equals...)
+* __message__ - the message the assertion method was called with (optional)
+
+The __assertionList__ object:
+
+* An array-like object with the following new attributes:
+ * __failures()__ - the number of assertions which failed
+ * __duration__ - the time taken for the test to complete in msecs
+
+For a reference implementation of a test reporter, see lib/reporters/default.js in
+the nodeunit project directory.
+
+
+Sandbox utility
+---------------
+
+This is a function which evaluates JavaScript files in a sandbox and returns the
+context. The sandbox function can be used for testing client-side code or private
+un-exported functions within a module.
+
+ var sandbox = require('nodeunit').utils.sandbox;
+ var example = sandbox('example.js');
+
+__sandbox(files, sandbox)__ - Evaluates JavaScript files in a sandbox, returning
+the context. The first argument can either be a single filename or an array of
+filenames. If multiple filenames are given their contents are concatenated before
+evalution. The second argument is an optional context to use for the sandbox.
+
+
+Running the nodeunit Tests
+--------------------------
+
+The tests for nodeunit are written using nodeunit itself as the test framework.
+However, the module test-base.js first does some basic tests using the assert
+module to ensure that test functions are actually run, and a basic level of
+nodeunit functionality is available.
+
+To run the nodeunit tests do:
+
+ make test
+
+__Note:__ There was a bug in node v0.2.0 causing the tests to hang, upgrading
+to v0.2.1 fixes this.
+
+
+Contributing
+------------
+
+Contributions to the project are most welcome, so feel free to fork and improve.
+When submitting a pull request, please run 'make lint' first to ensure
+we're following a consistent coding style.
+
108 node_modules/nodeunit/bin/nodeunit
@@ -0,0 +1,108 @@
+#!/usr/bin/env node
+
+var
+ fs = require('fs'),
+ sys = require('sys'),
+ path = require('path');
+
+require.paths.push(process.cwd());
+var args = process.ARGV.slice(2);
+
+var files = [];
+
+var testrunner,
+ config_file,
+ config_param_found = false,
+ output_param_found = false,
+ reporter_file = 'default',
+ reporter_param_found = false;
+
+var usage = "Usage: nodeunit [options] testmodule1.js testfolder [...] \n" +
+ "Options:\n\n" +
+ " --config FILE the path to a JSON file with options\n" +
+ " --reporter FILE optional path to a reporter file to customize the output\n" +
+ " --list-reporters list available build-in reporters\n" +
+ " -h, --help display this help and exit\n" +
+ " -v, --version output version information and exit";
+
+
+// load default options
+var content = fs.readFileSync(__dirname + '/nodeunit.json', 'utf8');
+var options = JSON.parse(content);
+
+// a very basic pseudo --options parser
+args.forEach(function (arg) {
+ if (arg.slice(0, 9) === "--config=") {
+ config_file = arg.slice(9);
+ } else if (arg === '--config') {
+ config_param_found = true;
+ } else if (config_param_found) {
+ config_file = arg;
+ config_param_found = false;
+ } else if (arg.slice(0, 9) === "--output=") {
+ options.output = arg.slice(9);
+ } else if (arg === '--output') {
+ output_param_found = true;
+ } else if (output_param_found) {
+ options.output = arg;
+ output_param_found = false;
+ } else if (arg.slice(0, 11) === "--reporter=") {
+ reporter_file = arg.slice(11);
+ } else if (arg === '--reporter') {
+ reporter_param_found = true;
+ } else if (reporter_param_found) {
+ reporter_file = arg;
+ reporter_param_found = false;
+ } else if (arg === '--list-reporters') {
+ var reporters = fs.readdirSync(__dirname + '/../lib/reporters');
+ reporters = reporters.filter(function (reporter_file) {
+ return (/\.js$/).test(reporter_file);
+ }).map(function (reporter_file) {
+ return reporter_file.replace(/\.js$/, '');
+ }).filter(function (reporter_file) {
+ return reporter_file !== 'index';
+ });
+ sys.puts('Build-in reporters: ');
+ reporters.forEach(function (reporter_file) {
+ var reporter = require('../lib/reporters/' + reporter_file);
+ sys.puts(' * ' + reporter_file + (reporter.info ? ': ' + reporter.info : ''));
+ });
+ process.exit(0);
+ } else if ((arg === '-v') || (arg === '--version')) {
+ var content = fs.readFileSync(__dirname + '/../package.json', 'utf8');
+ var pkg = JSON.parse(content);
+ sys.puts(pkg.version);
+ process.exit(0);
+ } else if ((arg === '-h') || (arg === '--help')) {
+ sys.puts(usage);
+ process.exit(0);
+ } else {
+ files.push(arg);
+ }
+});
+
+if (files.length === 0) {
+ sys.puts('Files required.');
+ sys.puts(usage);
+ process.exit(1);
+}
+
+if (config_file) {
+ content = fs.readFileSync(config_file, 'utf8');
+ var custom_options = JSON.parse(content);
+
+ for (var option in custom_options) {
+ if (typeof option === 'string') {
+ options[option] = custom_options[option];
+ }
+ }
+}
+
+var builtin_reporters = require(__dirname + '/../lib/reporters');
+if (reporter_file in builtin_reporters) {
+ testrunner = builtin_reporters[reporter_file];
+}
+else {
+ testrunner = require(reporter_file);
+}
+testrunner.run(files, options);
10 node_modules/nodeunit/bin/nodeunit.json
@@ -0,0 +1,10 @@
+{
+ "error_prefix": "\u001B[31m",
+ "error_suffix": "\u001B[39m",
+ "ok_prefix": "\u001B[32m",
+ "ok_suffix": "\u001B[39m",
+ "bold_prefix": "\u001B[1m",
+ "bold_suffix": "\u001B[22m",
+ "assertion_prefix": "\u001B[35m",
+ "assertion_suffix": "\u001B[39m"
+}
623 node_modules/nodeunit/deps/async.js
@@ -0,0 +1,623 @@
+/*global setTimeout: false, console: false */
+(function () {
+
+ var async = {};
+
+ // global on the server, window in the browser
+ var root = this,
+ previous_async = root.async;
+
+ if (typeof module !== 'undefined' && module.exports) {
+ module.exports = async;
+ }
+ else {
+ root.async = async;
+ }
+
+ async.noConflict = function () {
+ root.async = previous_async;
+ return async;
+ };
+
+ //// cross-browser compatiblity functions ////
+
+ var _forEach = function (arr, iterator) {
+ if (arr.forEach) {
+ return arr.forEach(iterator);
+ }
+ for (var i = 0; i < arr.length; i += 1) {
+ iterator(arr[i], i, arr);
+ }
+ };
+
+ var _map = function (arr, iterator) {
+ if (arr.map) {
+ return arr.map(iterator);
+ }
+ var results = [];
+ _forEach(arr, function (x, i, a) {
+ results.push(iterator(x, i, a));
+ });
+ return results;
+ };
+
+ var _reduce = function (arr, iterator, memo) {
+ if (arr.reduce) {
+ return arr.reduce(iterator, memo);
+ }
+ _forEach(arr, function (x, i, a) {
+ memo = iterator(memo, x, i, a);
+ });
+ return memo;
+ };
+
+ var _keys = function (obj) {
+ if (Object.keys) {
+ return Object.keys(obj);
+ }
+ var keys = [];
+ for (var k in obj) {
+ if (obj.hasOwnProperty(k)) {
+ keys.push(k);
+ }
+ }
+ return keys;
+ };
+
+ var _indexOf = function (arr, item) {
+ if (arr.indexOf) {
+ return arr.indexOf(item);
+ }
+ for (var i = 0; i < arr.length; i += 1) {
+ if (arr[i] === item) {
+ return i;
+ }
+ }
+ return -1;
+ };
+
+ //// exported async module functions ////
+
+ //// nextTick implementation with browser-compatible fallback ////
+ if (typeof process === 'undefined' || !(process.nextTick)) {
+ async.nextTick = function (fn) {
+ setTimeout(fn, 0);
+ };
+ }
+ else {
+ async.nextTick = process.nextTick;
+ }
+
+ async.forEach = function (arr, iterator, callback) {
+ if (!arr.length) {
+ return callback();
+ }
+ var completed = 0;
+ _forEach(arr, function (x) {
+ iterator(x, function (err) {
+ if (err) {
+ callback(err);
+ callback = function () {};
+ }
+ else {
+ completed += 1;
+ if (completed === arr.length) {
+ callback();
+ }
+ }
+ });
+ });
+ };
+
+ async.forEachSeries = function (arr, iterator, callback) {
+ if (!arr.length) {
+ return callback();
+ }
+ var completed = 0;
+ var iterate = function () {
+ iterator(arr[completed], function (err) {
+ if (err) {
+ callback(err);
+ callback = function () {};
+ }
+ else {
+ completed += 1;
+ if (completed === arr.length) {
+ callback();
+ }
+ else {
+ iterate();
+ }
+ }
+ });
+ };
+ iterate();
+ };
+
+
+ var doParallel = function (fn) {
+ return function () {
+ var args = Array.prototype.slice.call(arguments);
+ return fn.apply(null, [async.forEach].concat(args));
+ };
+ };
+ var doSeries = function (fn) {
+ return function () {
+ var args = Array.prototype.slice.call(arguments);
+ return fn.apply(null, [async.forEachSeries].concat(args));
+ };
+ };
+
+
+ var _asyncMap = function (eachfn, arr, iterator, callback) {
+ var results = [];
+ arr = _map(arr, function (x, i) {
+ return {index: i, value: x};
+ });
+ eachfn(arr, function (x, callback) {
+ iterator(x.value, function (err, v) {
+ results[x.index] = v;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, results);
+ });
+ };
+ async.map = doParallel(_asyncMap);
+ async.mapSeries = doSeries(_asyncMap);
+
+
+ // reduce only has a series version, as doing reduce in parallel won't
+ // work in many situations.
+ async.reduce = function (arr, memo, iterator, callback) {
+ async.forEachSeries(arr, function (x, callback) {
+ iterator(memo, x, function (err, v) {
+ memo = v;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, memo);
+ });
+ };
+ // inject alias
+ async.inject = async.reduce;
+ // foldl alias
+ async.foldl = async.reduce;
+
+ async.reduceRight = function (arr, memo, iterator, callback) {
+ var reversed = _map(arr, function (x) {
+ return x;
+ }).reverse();
+ async.reduce(reversed, memo, iterator, callback);
+ };
+ // foldr alias
+ async.foldr = async.reduceRight;
+
+ var _filter = function (eachfn, arr, iterator, callback) {
+ var results = [];
+ arr = _map(arr, function (x, i) {
+ return {index: i, value: x};
+ });
+ eachfn(arr, function (x, callback) {
+ iterator(x.value, function (v) {
+ if (v) {
+ results.push(x);
+ }
+ callback();
+ });
+ }, function (err) {
+ callback(_map(results.sort(function (a, b) {
+ return a.index - b.index;
+ }), function (x) {
+ return x.value;
+ }));
+ });
+ };
+ async.filter = doParallel(_filter);
+ async.filterSeries = doSeries(_filter);
+ // select alias
+ async.select = async.filter;
+ async.selectSeries = async.filterSeries;
+
+ var _reject = function (eachfn, arr, iterator, callback) {
+ var results = [];
+ arr = _map(arr, function (x, i) {
+ return {index: i, value: x};
+ });
+ eachfn(arr, function (x, callback) {
+ iterator(x.value, function (v) {
+ if (!v) {
+ results.push(x);
+ }
+ callback();
+ });
+ }, function (err) {
+ callback(_map(results.sort(function (a, b) {
+ return a.index - b.index;
+ }), function (x) {
+ return x.value;
+ }));
+ });
+ };
+ async.reject = doParallel(_reject);
+ async.rejectSeries = doSeries(_reject);
+
+ var _detect = function (eachfn, arr, iterator, main_callback) {
+ eachfn(arr, function (x, callback) {
+ iterator(x, function (result) {
+ if (result) {
+ main_callback(x);
+ }
+ else {
+ callback();
+ }
+ });
+ }, function (err) {
+ main_callback();
+ });
+ };
+ async.detect = doParallel(_detect);
+ async.detectSeries = doSeries(_detect);
+
+ async.some = function (arr, iterator, main_callback) {
+ async.forEach(arr, function (x, callback) {
+ iterator(x, function (v) {
+ if (v) {
+ main_callback(true);
+ main_callback = function () {};
+ }
+ callback();
+ });
+ }, function (err) {
+ main_callback(false);
+ });
+ };
+ // any alias
+ async.any = async.some;
+
+ async.every = function (arr, iterator, main_callback) {
+ async.forEach(arr, function (x, callback) {
+ iterator(x, function (v) {
+ if (!v) {
+ main_callback(false);
+ main_callback = function () {};
+ }
+ callback();
+ });
+ }, function (err) {
+ main_callback(true);
+ });
+ };
+ // all alias
+ async.all = async.every;
+
+ async.sortBy = function (arr, iterator, callback) {
+ async.map(arr, function (x, callback) {
+ iterator(x, function (err, criteria) {
+ if (err) {
+ callback(err);
+ }
+ else {
+ callback(null, {value: x, criteria: criteria});
+ }
+ });
+ }, function (err, results) {
+ if (err) {
+ return callback(err);
+ }
+ else {
+ var fn = function (left, right) {
+ var a = left.criteria, b = right.criteria;
+ return a < b ? -1 : a > b ? 1 : 0;
+ };
+ callback(null, _map(results.sort(fn), function (x) {
+ return x.value;
+ }));
+ }
+ });
+ };
+
+ async.auto = function (tasks, callback) {
+ callback = callback || function () {};
+ var keys = _keys(tasks);
+ if (!keys.length) {
+ return callback(null);
+ }
+
+ var completed = [];
+
+ var listeners = [];
+ var addListener = function (fn) {
+ listeners.unshift(fn);
+ };
+ var removeListener = function (fn) {
+ for (var i = 0; i < listeners.length; i += 1) {
+ if (listeners[i] === fn) {
+ listeners.splice(i, 1);
+ return;
+ }
+ }
+ };
+ var taskComplete = function () {
+ _forEach(listeners, function (fn) {
+ fn();
+ });
+ };
+
+ addListener(function () {
+ if (completed.length === keys.length) {
+ callback(null);
+ }
+ });
+
+ _forEach(keys, function (k) {
+ var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k];
+ var taskCallback = function (err) {
+ if (err) {
+ callback(err);
+ // stop subsequent errors hitting callback multiple times
+ callback = function () {};
+ }
+ else {
+ completed.push(k);
+ taskComplete();
+ }
+ };
+ var requires = task.slice(0, Math.abs(task.length - 1)) || [];
+ var ready = function () {
+ return _reduce(requires, function (a, x) {
+ return (a && _indexOf(completed, x) !== -1);
+ }, true);
+ };
+ if (ready()) {
+ task[task.length - 1](taskCallback);
+ }
+ else {
+ var listener = function () {
+ if (ready()) {
+ removeListener(listener);
+ task[task.length - 1](taskCallback);
+ }
+ };
+ addListener(listener);
+ }
+ });
+ };
+
+ async.waterfall = function (tasks, callback) {
+ if (!tasks.length) {
+ return callback();
+ }
+ callback = callback || function () {};
+ var wrapIterator = function (iterator) {
+ return function (err) {
+ if (err) {
+ callback(err);
+ callback = function () {};
+ }
+ else {
+ var args = Array.prototype.slice.call(arguments, 1);
+ var next = iterator.next();
+ if (next) {
+ args.push(wrapIterator(next));
+ }
+ else {
+ args.push(callback);
+ }
+ async.nextTick(function () {
+ iterator.apply(null, args);
+ });
+ }
+ };
+ };
+ wrapIterator(async.iterator(tasks))();
+ };
+
+ async.parallel = function (tasks, callback) {
+ callback = callback || function () {};
+ if (tasks.constructor === Array) {
+ async.map(tasks, function (fn, callback) {
+ if (fn) {
+ fn(function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ callback.call(null, err, args || null);
+ });
+ }
+ }, callback);
+ }
+ else {
+ var results = {};
+ async.forEach(_keys(tasks), function (k, callback) {
+ tasks[k](function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ results[k] = args;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, results);
+ });
+ }
+ };
+
+ async.series = function (tasks, callback) {
+ callback = callback || function () {};
+ if (tasks.constructor === Array) {
+ async.mapSeries(tasks, function (fn, callback) {
+ if (fn) {
+ fn(function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ callback.call(null, err, args || null);
+ });
+ }
+ }, callback);
+ }
+ else {
+ var results = {};
+ async.forEachSeries(_keys(tasks), function (k, callback) {
+ tasks[k](function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ results[k] = args;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, results);
+ });
+ }
+ };
+
+ async.iterator = function (tasks) {
+ var makeCallback = function (index) {
+ var fn = function () {
+ if (tasks.length) {
+ tasks[index].apply(null, arguments);
+ }
+ return fn.next();
+ };
+ fn.next = function () {
+ return (index < tasks.length - 1) ? makeCallback(index + 1): null;
+ };
+ return fn;
+ };
+ return makeCallback(0);
+ };
+
+ async.apply = function (fn) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return function () {
+ return fn.apply(
+ null, args.concat(Array.prototype.slice.call(arguments))
+ );
+ };
+ };
+
+ var _concat = function (eachfn, arr, fn, callback) {
+ var r = [];
+ eachfn(arr, function (x, cb) {
+ fn(x, function (err, y) {
+ r = r.concat(y || []);
+ cb(err);
+ });
+ }, function (err) {
+ callback(err, r);
+ });
+ };
+ async.concat = doParallel(_concat);
+ async.concatSeries = doSeries(_concat);
+
+ async.whilst = function (test, iterator, callback) {
+ if (test()) {
+ iterator(function (err) {
+ if (err) {
+ return callback(err);
+ }
+ async.whilst(test, iterator, callback);
+ });
+ }
+ else {
+ callback();
+ }
+ };
+
+ async.until = function (test, iterator, callback) {
+ if (!test()) {
+ iterator(function (err) {
+ if (err) {
+ return callback(err);
+ }
+ async.until(test, iterator, callback);
+ });
+ }
+ else {
+ callback();
+ }
+ };
+
+ async.queue = function (worker, concurrency) {
+ var workers = 0;
+ var tasks = [];
+ var q = {
+ concurrency: concurrency,
+ push: function (data, callback) {
+ tasks.push({data: data, callback: callback});
+ async.nextTick(q.process);
+ },
+ process: function () {
+ if (workers < q.concurrency && tasks.length) {
+ var task = tasks.splice(0, 1)[0];
+ workers += 1;
+ worker(task.data, function () {
+ workers -= 1;
+ if (task.callback) {
+ task.callback.apply(task, arguments);
+ }
+ q.process();
+ });
+ }
+ },
+ length: function () {
+ return tasks.length;
+ }
+ };
+ return q;
+ };
+
+ var _console_fn = function (name) {
+ return function (fn) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ fn.apply(null, args.concat([function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (typeof console !== 'undefined') {
+ if (err) {
+ if (console.error) {
+ console.error(err);
+ }
+ }
+ else if (console[name]) {
+ _forEach(args, function (x) {
+ console[name](x);
+ });
+ }
+ }
+ }]));
+ };
+ };
+ async.log = _console_fn('log');
+ async.dir = _console_fn('dir');
+ /*async.info = _console_fn('info');
+ async.warn = _console_fn('warn');
+ async.error = _console_fn('error');*/
+
+ async.memoize = function (fn, hasher) {
+ var memo = {};
+ hasher = hasher || function (x) {
+ return x;
+ };
+ return function () {
+ var args = Array.prototype.slice.call(arguments);
+ var callback = args.pop();
+ var key = hasher.apply(null, args);
+ if (key in memo) {
+ callback.apply(null, memo[key]);
+ }
+ else {
+ fn.apply(null, args.concat([function () {
+ memo[key] = arguments;
+ callback.apply(null, arguments);
+ }]));
+ }
+ };
+ };
+
+}());
125 node_modules/nodeunit/deps/ejs.js
@@ -0,0 +1,125 @@
+
+/*!
+ * EJS
+ * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
+ * MIT Licensed
+ */
+
+/**
+ * Module dependencies.
+ */
+
+var sys = require('sys');
+
+/**
+ * Library version.
+ */
+
+exports.version = '0.0.3';
+
+/**
+ * Intermediate js cache.
+ *
+ * @type Object
+ */
+
+var cache = {};
+
+/**
+ * Clear intermediate js cache.
+ *
+ * @api public
+ */
+
+exports.clearCache = function(){
+ cache = {};
+};
+
+/**
+ * Escape the given string of `html`.
+ *
+ * @param {String} html
+ * @return {String}
+ * @api private
+ */
+
+function escape(html){
+ return String(html)
+ .replace(/&(?!\w+;)/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+/**
+ * Parse the given `str` of ejs, returning the function body.
+ *
+ * @param {String} str
+ * @return {String}
+ * @api public
+ */
+
+var parse = exports.parse = function(str){
+ return 'var buf = [];\n'
+ + "with (locals) {\nbuf.push('"
+ + String(str)
+ .replace(/[\r\t]/g, " ")
+ .replace(/\n/g, "\\n")
+ .split("<%").join("\t")
+ .replace(/((^|%>)[^\t]*)'/g, "$1\r")
+ .replace(/\t=(.*?)%>/g, "', escape($1) ,'")
+ .replace(/\t-(.*?)%>/g, "', $1 ,'")
+ .split("\t").join("');")
+ .split("%>").join("buf.push('")
+ .split("\r").join("\\'")
+ + "');\n}\nreturn buf.join('');";
+};
+
+/**
+ * Compile the given `str` of ejs into a `Function`.
+ *
+ * @param {String} str
+ * @param {Object} options
+ * @return {Function}
+ * @api public
+ */
+
+var compile = exports.compile = function(str, options){
+ if (options.debug) sys.puts(parse(str));
+ return new Function('locals, escape', parse(str));
+};
+
+/**
+ * Render the given `str` of ejs.
+ *
+ * Options:
+ *
+ * - `locals` Local variables object
+ * - `cache` Compiled functions are cached, requires `filename`
+ * - `filename` Used by `cache` to key caches
+ * - `context|scope` Function execution context
+ * - `debug` Output generated function body
+ *
+ * @param {String} str
+ * @param {Object} options
+ * @return {String}
+ * @api public
+ */
+
+exports.render = function(str, options){
+ var fn,
+ options = options || {};
+ if (options.cache) {
+ if (options.filename) {
+ fn = cache[options.filename] = compile(str, options);
+ } else {
+ throw new Error('"cache" option requires "filename".');
+ }
+ } else {
+ fn = compile(str, options);
+ }
+ return fn.call(
+ options.context || options.scope,
+ options.locals || {},
+ escape);
+};
483 node_modules/nodeunit/deps/json2.js
@@ -0,0 +1,483 @@
+/*
+ http://www.JSON.org/json2.js
+ 2010-11-17
+
+ Public Domain.
+
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+ See http://www.JSON.org/js.html
+
+
+ This code should be minified before deployment.
+ See http://javascript.crockford.com/jsmin.html
+
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+ NOT CONTROL.
+
+
+ This file creates a global JSON object containing two methods: stringify
+ and parse.
+
+ JSON.stringify(value, replacer, space)
+ value any JavaScript value, usually an object or array.
+
+ replacer an optional parameter that determines how object
+ values are stringified for objects. It can be a
+ function or an array of strings.
+
+ space an optional parameter that specifies the indentation
+ of nested structures. If it is omitted, the text will
+ be packed without extra whitespace. If it is a number,
+ it will specify the number of spaces to indent at each
+ level. If it is a string (such as '\t' or '&nbsp;'),
+ it contains the characters used to indent at each level.
+
+ This method produces a JSON text from a JavaScript value.
+
+ When an object value is found, if the object contains a toJSON
+ method, its toJSON method will be called and the result will be
+ stringified. A toJSON method does not serialize: it returns the
+ value represented by the name/value pair that should be serialized,
+ or undefined if nothing should be serialized. The toJSON method
+ will be passed the key associated with the value, and this will be
+ bound to the value
+
+ For example, this would serialize Dates as ISO strings.
+
+ Date.prototype.toJSON = function (key) {
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ return this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z';
+ };
+
+ You can provide an optional replacer method. It will be passed the
+ key and value of each member, with this bound to the containing
+ object. The value that is returned from your method will be
+ serialized. If your method returns undefined, then the member will
+ be excluded from the serialization.
+
+ If the replacer parameter is an array of strings, then it will be
+ used to select the members to be serialized. It filters the results
+ such that only members with keys listed in the replacer array are
+ stringified.
+
+ Values that do not have JSON representations, such as undefined or
+ functions, will not be serialized. Such values in objects will be
+ dropped; in arrays they will be replaced with null. You can use
+ a replacer function to replace those with JSON values.
+ JSON.stringify(undefined) returns undefined.
+
+ The optional space parameter produces a stringification of the
+ value that is filled with line breaks and indentation to make it
+ easier to read.
+
+ If the space parameter is a non-empty string, then that string will
+ be used for indentation. If the space parameter is a number, then
+ the indentation will be that many spaces.
+
+ Example:
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}]);
+ // text is '["e",{"pluribus":"unum"}]'
+
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
+ // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
+
+ text = JSON.stringify([new Date()], function (key, value) {
+ return this[key] instanceof Date ?
+ 'Date(' + this[key] + ')' : value;
+ });
+ // text is '["Date(---current time---)"]'
+
+
+ JSON.parse(text, reviver)
+ This method parses a JSON text to produce an object or array.
+ It can throw a SyntaxError exception.
+
+ The optional reviver parameter is a function that can filter and
+ transform the results. It receives each of the keys and values,
+ and its return value is used instead of the original value.
+ If it returns what it received, then the structure is not modified.
+ If it returns undefined then the member is deleted.
+
+ Example:
+
+ // Parse the text. Values that look like ISO date strings will
+ // be converted to Date objects.
+
+ myData = JSON.parse(text, function (key, value) {
+ var a;
+ if (typeof value === 'string') {
+ a =
+/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
+ if (a) {
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+ +a[5], +a[6]));
+ }
+ }
+ return value;
+ });
+
+ myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
+ var d;
+ if (typeof value === 'string' &&
+ value.slice(0, 5) === 'Date(' &&
+ value.slice(-1) === ')') {
+ d = new Date(value.slice(5, -1));
+ if (d) {
+ return d;
+ }
+ }
+ return value;
+ });
+
+
+ This is a reference implementation. You are free to copy, modify, or
+ redistribute.
+*/
+
+/*jslint evil: true, strict: false, regexp: false */
+
+/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
+ call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
+ getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
+ lastIndex, length, parse, prototype, push, replace, slice, stringify,
+ test, toJSON, toString, valueOf
+*/
+
+
+// Create a JSON object only if one does not already exist. We create the
+// methods in a closure to avoid creating global variables.
+
+if (!this.JSON) {
+ this.JSON = {};
+}
+
+(function () {
+ "use strict";
+
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ if (typeof Date.prototype.toJSON !== 'function') {
+
+ Date.prototype.toJSON = function (key) {
+
+ return isFinite(this.valueOf()) ?
+ this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z' : null;
+ };
+
+ String.prototype.toJSON =
+ Number.prototype.toJSON =
+ Boolean.prototype.toJSON = function (key) {
+ return this.valueOf();
+ };
+ }
+
+ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ gap,
+ indent,
+ meta = { // table of character substitutions
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '"' : '\\"',
+ '\\': '\\\\'
+ },
+ rep;
+
+
+ function quote(string) {
+
+// If the string contains no control characters, no quote characters, and no
+// backslash characters, then we can safely slap some quotes around it.
+// Otherwise we must also replace the offending characters with safe escape
+// sequences.
+
+ escapable.lastIndex = 0;
+ return escapable.test(string) ?
+ '"' + string.replace(escapable, function (a) {
+ var c = meta[a];
+ return typeof c === 'string' ? c :
+ '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ }) + '"' :
+ '"' + string + '"';
+ }
+
+
+ function str(key, holder) {
+
+// Produce a string from holder[key].
+
+ var i, // The loop counter.
+ k, // The member key.
+ v, // The member value.
+ length,
+ mind = gap,
+ partial,
+ value = holder[key];
+
+// If the value has a toJSON method, call it to obtain a replacement value.
+
+ if (value && typeof value === 'object' &&
+ typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ }
+
+// If we were called with a replacer function, then call the replacer to
+// obtain a replacement value.
+
+ if (typeof rep === 'function') {
+ value = rep.call(holder, key, value);
+ }
+
+// What happens next depends on the value's type.
+
+ switch (typeof value) {
+ case 'string':
+ return quote(value);
+
+ case 'number':
+
+// JSON numbers must be finite. Encode non-finite numbers as null.
+
+ return isFinite(value) ? String(value) : 'null';
+
+ case 'boolean':
+ case 'null':
+
+// If the value is a boolean or null, convert it to a string. Note:
+// typeof null does not produce 'null'. The case is included here in
+// the remote chance that this gets fixed someday.
+
+ return String(value);
+
+// If the type is 'object', we might be dealing with an object or an array or
+// null.
+
+ case 'object':
+
+// Due to a specification blunder in ECMAScript, typeof null is 'object',
+// so watch out for that case.
+
+ if (!value) {
+ return 'null';
+ }
+
+// Make an array to hold the partial results of stringifying this object value.
+
+ gap += indent;
+ partial = [];
+
+// Is the value an array?
+
+ if (Object.prototype.toString.apply(value) === '[object Array]') {
+
+// The value is an array. Stringify every element. Use null as a placeholder
+// for non-JSON values.
+
+ length = value.length;
+ for (i = 0; i < length; i += 1) {
+ partial[i] = str(i, value) || 'null';
+ }
+
+// Join all of the elements together, separated with commas, and wrap them in
+// brackets.
+
+ v = partial.length === 0 ? '[]' :
+ gap ? '[\n' + gap +
+ partial.join(',\n' + gap) + '\n' +
+ mind + ']' :
+ '[' + partial.join(',') + ']';
+ gap = mind;
+ return v;
+ }
+
+// If the replacer is an array, use it to select the members to be stringified.
+
+ if (rep && typeof rep === 'object') {
+ length = rep.length;
+ for (i = 0; i < length; i += 1) {
+ k = rep[i];
+ if (typeof k === 'string') {
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ } else {
+
+// Otherwise, iterate through all of the keys in the object.
+
+ for (k in value) {
+ if (Object.hasOwnProperty.call(value, k)) {
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ }
+
+// Join all of the member texts together, separated with commas,
+// and wrap them in braces.
+
+ v = partial.length === 0 ? '{}' :
+ gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
+ mind + '}' : '{' + partial.join(',') + '}';
+ gap = mind;
+ return v;
+ }
+ }
+
+// If the JSON object does not yet have a stringify method, give it one.
+
+ if (typeof JSON.stringify !== 'function') {
+ JSON.stringify = function (value, replacer, space) {
+
+// The stringify method takes a value and an optional replacer, and an optional
+// space parameter, and returns a JSON text. The replacer can be a function
+// that can replace values, or an array of strings that will select the keys.
+// A default replacer method can be provided. Use of the space parameter can
+// produce text that is more easily readable.
+
+ var i;
+ gap = '';
+ indent = '';
+
+// If the space parameter is a number, make an indent string containing that
+// many spaces.
+
+ if (typeof space === 'number') {
+ for (i = 0; i < space; i += 1) {
+ indent += ' ';
+ }
+
+// If the space parameter is a string, it will be used as the indent string.
+
+ } else if (typeof space === 'string') {
+ indent = space;
+ }
+
+// If there is a replacer, it must be a function or an array.
+// Otherwise, throw an error.
+
+ rep = replacer;
+ if (replacer && typeof replacer !== 'function' &&
+ (typeof replacer !== 'object' ||
+ typeof replacer.length !== 'number')) {
+ throw new Error('JSON.stringify');
+ }
+
+// Make a fake root object containing our value under the key of ''.
+// Return the result of stringifying the value.
+
+ return str('', {'': value});
+ };
+ }
+
+
+// If the JSON object does not yet have a parse method, give it one.
+
+ if (typeof JSON.parse !== 'function') {
+ JSON.parse = function (text, reviver) {
+
+// The parse method takes a text and an optional reviver function, and returns
+// a JavaScript value if the text is a valid JSON text.
+
+ var j;
+
+ function walk(holder, key) {
+
+// The walk method is used to recursively walk the resulting structure so
+// that modifications can be made.
+
+ var k, v, value = holder[key];
+ if (value && typeof value === 'object') {
+ for (k in value) {
+ if (Object.hasOwnProperty.call(value, k)) {
+ v = walk(value, k);
+ if (v !== undefined) {
+ value[k] = v;
+ } else {
+ delete value[k];
+ }
+ }
+ }
+ }
+ return reviver.call(holder, key, value);
+ }
+
+
+// Parsing happens in four stages. In the first stage, we replace certain
+// Unicode characters with escape sequences. JavaScript handles many characters
+// incorrectly, either silently deleting them, or treating them as line endings.
+
+ text = String(text);
+ cx.lastIndex = 0;
+ if (cx.test(text)) {
+ text = text.replace(cx, function (a) {
+ return '\\u' +
+ ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ });
+ }
+
+// In the second stage, we run the text against regular expressions that look
+// for non-JSON patterns. We are especially concerned with '()' and 'new'
+// because they can cause invocation, and '=' because it can cause mutation.
+// But just to be safe, we want to reject all unexpected forms.
+
+// We split the second stage into 4 regexp operations in order to work around
+// crippling inefficiencies in IE's and Safari's regexp engines. First we
+// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
+// replace all simple value tokens with ']' characters. Third, we delete all
+// open brackets that follow a colon or comma or that begin the text. Finally,
+// we look to see that the remaining characters are only whitespace or ']' or
+// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
+
+ if (/^[\],:{}\s]*$/
+.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
+.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
+.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
+
+// In the third stage we use the eval function to compile the text into a
+// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
+// in JavaScript: it can begin a block or an object literal. We wrap the text
+// in parens to eliminate the ambiguity.
+
+ j = eval('(' + text + ')');
+
+// In the optional fourth stage, we recursively walk the new structure, passing
+// each name/value pair to a reviver function for possible transformation.
+
+ return typeof reviver === 'function' ?
+ walk({'': j}, '') : j;
+ }
+
+// If the text is not JSON parseable, then a SyntaxError is thrown.
+
+ throw new SyntaxError('JSON.parse');
+ };
+ }
+}());
60 node_modules/nodeunit/doc/nodeunit.md
@@ -0,0 +1,60 @@
+nodeunit(1) -- simple node.js unit testing tool
+===============================================
+
+## SYNOPSIS
+
+ nodeunit [options] <file-or-directory> [<file-or-directory> ...]
+
+## DESCRIPTION
+
+Nodeunit is a simple unit testing tool based on the node.js assert module.
+
+* Simple to use
+* Just export the tests from a module
+* Helps you avoid common pitfalls when testing asynchronous code
+* Easy to add test cases with setUp and tearDown functions if you wish
+* Allows the use of mocks and stubs
+
+## OPTIONS
+
+ __--config FILE__:
+ Load config options from a JSON file, allows the customisation
+ of color schemes for the default test reporter etc.
+ See bin/nodeunit.json for current available options.
+
+ __--reporter FILE__:
+ You can set the test reporter to a custom module or on of the modules
+ in nodeunit/lib/reporters, when omitted, the default test runner is used.
+
+ __--list-reporters__:
+ List available build-in reporters.
+
+ __-h__, __--help__:
+ Display the help and exit.
+
+ __-v__, __--version__:
+ Output version information and exit.
+
+ __<file-or-directory>__:
+ You can run nodeunit on specific files or on all *\*.js* files inside
+ a directory.
+
+## AUTHORS
+
+Written by Caolan McMahon and other nodeunit contributors.
+Contributors list: <http://github.com/caolan/nodeunit/contributors>.
+
+## REPORTING BUGS
+
+Report nodeunit bugs to <http://github.com/caolan/nodeunit/issues>.
+
+## COPYRIGHT
+
+Copyright © 2010 Caolan McMahon.
+Nodeunit has been released under the MIT license:
+<http://github.com/caolan/nodeunit/raw/master/LICENSE>.
+
+## SEE ALSO
+
+node(1)
+
1,757 node_modules/nodeunit/examples/browser/nodeunit.js
@@ -0,0 +1,1757 @@
+/*!
+ * Nodeunit
+ * https://github.com/caolan/nodeunit
+ * Copyright (c) 2010 Caolan McMahon
+ * MIT Licensed
+ *
+ * json2.js
+ * http://www.JSON.org/json2.js
+ * Public Domain.
+ * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+ */
+nodeunit = (function(){
+/*
+ http://www.JSON.org/json2.js
+ 2010-11-17
+
+ Public Domain.
+
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+ See http://www.JSON.org/js.html
+
+
+ This code should be minified before deployment.
+ See http://javascript.crockford.com/jsmin.html
+
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+ NOT CONTROL.
+
+
+ This file creates a global JSON object containing two methods: stringify
+ and parse.
+
+ JSON.stringify(value, replacer, space)
+ value any JavaScript value, usually an object or array.
+
+ replacer an optional parameter that determines how object
+ values are stringified for objects. It can be a
+ function or an array of strings.
+
+ space an optional parameter that specifies the indentation
+ of nested structures. If it is omitted, the text will
+ be packed without extra whitespace. If it is a number,
+ it will specify the number of spaces to indent at each
+ level. If it is a string (such as '\t' or '&nbsp;'),
+ it contains the characters used to indent at each level.
+
+ This method produces a JSON text from a JavaScript value.
+
+ When an object value is found, if the object contains a toJSON
+ method, its toJSON method will be called and the result will be
+ stringified. A toJSON method does not serialize: it returns the
+ value represented by the name/value pair that should be serialized,
+ or undefined if nothing should be serialized. The toJSON method
+ will be passed the key associated with the value, and this will be
+ bound to the value
+
+ For example, this would serialize Dates as ISO strings.
+
+ Date.prototype.toJSON = function (key) {
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ return this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z';
+ };
+
+ You can provide an optional replacer method. It will be passed the
+ key and value of each member, with this bound to the containing
+ object. The value that is returned from your method will be
+ serialized. If your method returns undefined, then the member will
+ be excluded from the serialization.
+
+ If the replacer parameter is an array of strings, then it will be
+ used to select the members to be serialized. It filters the results
+ such that only members with keys listed in the replacer array are
+ stringified.
+
+ Values that do not have JSON representations, such as undefined or
+ functions, will not be serialized. Such values in objects will be
+ dropped; in arrays they will be replaced with null. You can use
+ a replacer function to replace those with JSON values.
+ JSON.stringify(undefined) returns undefined.
+
+ The optional space parameter produces a stringification of the
+ value that is filled with line breaks and indentation to make it
+ easier to read.
+
+ If the space parameter is a non-empty string, then that string will
+ be used for indentation. If the space parameter is a number, then
+ the indentation will be that many spaces.
+
+ Example:
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}]);
+ // text is '["e",{"pluribus":"unum"}]'
+
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
+ // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
+
+ text = JSON.stringify([new Date()], function (key, value) {
+ return this[key] instanceof Date ?
+ 'Date(' + this[key] + ')' : value;
+ });
+ // text is '["Date(---current time---)"]'
+
+
+ JSON.parse(text, reviver)
+ This method parses a JSON text to produce an object or array.
+ It can throw a SyntaxError exception.
+
+ The optional reviver parameter is a function that can filter and
+ transform the results. It receives each of the keys and values,
+ and its return value is used instead of the original value.
+ If it returns what it received, then the structure is not modified.
+ If it returns undefined then the member is deleted.
+
+ Example:
+
+ // Parse the text. Values that look like ISO date strings will
+ // be converted to Date objects.
+
+ myData = JSON.parse(text, function (key, value) {
+ var a;
+ if (typeof value === 'string') {
+ a =
+/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
+ if (a) {
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+ +a[5], +a[6]));
+ }
+ }
+ return value;
+ });
+
+ myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
+ var d;
+ if (typeof value === 'string' &&
+ value.slice(0, 5) === 'Date(' &&
+ value.slice(-1) === ')') {
+ d = new Date(value.slice(5, -1));
+ if (d) {
+ return d;
+ }
+ }
+ return value;
+ });
+
+
+ This is a reference implementation. You are free to copy, modify, or
+ redistribute.
+*/
+
+/*jslint evil: true, strict: false, regexp: false */
+
+/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
+ call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
+ getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
+ lastIndex, length, parse, prototype, push, replace, slice, stringify,
+ test, toJSON, toString, valueOf
+*/
+
+
+// Create a JSON object only if one does not already exist. We create the
+// methods in a closure to avoid creating global variables.
+
+if (!this.JSON) {
+ this.JSON = {};
+}
+
+(function () {
+ "use strict";
+
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ if (typeof Date.prototype.toJSON !== 'function') {
+
+ Date.prototype.toJSON = function (key) {
+
+ return isFinite(this.valueOf()) ?
+ this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z' : null;
+ };
+
+ String.prototype.toJSON =
+ Number.prototype.toJSON =
+ Boolean.prototype.toJSON = function (key) {
+ return this.valueOf();
+ };
+ }
+
+ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ gap,
+ indent,
+ meta = { // table of character substitutions
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '"' : '\\"',
+ '\\': '\\\\'
+ },
+ rep;
+
+
+ function quote(string) {
+
+// If the string contains no control characters, no quote characters, and no
+// backslash characters, then we can safely slap some quotes around it.
+// Otherwise we must also replace the offending characters with safe escape
+// sequences.
+
+ escapable.lastIndex = 0;
+ return escapable.test(string) ?
+ '"' + string.replace(escapable, function (a) {
+ var c = meta[a];
+ return typeof c === 'string' ? c :
+ '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ }) + '"' :
+ '"' + string + '"';
+ }
+
+
+ function str(key, holder) {
+
+// Produce a string from holder[key].
+
+ var i, // The loop counter.
+ k, // The member key.
+ v, // The member value.
+ length,
+ mind = gap,
+ partial,
+ value = holder[key];
+
+// If the value has a toJSON method, call it to obtain a replacement value.
+
+ if (value && typeof value === 'object' &&
+ typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ }
+
+// If we were called with a replacer function, then call the replacer to
+// obtain a replacement value.
+
+ if (typeof rep === 'function') {
+ value = rep.call(holder, key, value);
+ }
+
+// What happens next depends on the value's type.
+
+ switch (typeof value) {
+ case 'string':
+ return quote(value);
+
+ case 'number':
+
+// JSON numbers must be finite. Encode non-finite numbers as null.
+
+ return isFinite(value) ? String(value) : 'null';
+
+ case 'boolean':
+ case 'null':
+
+// If the value is a boolean or null, convert it to a string. Note:
+// typeof null does not produce 'null'. The case is included here in
+// the remote chance that this gets fixed someday.
+
+ return String(value);
+
+// If the type is 'object', we might be dealing with an object or an array or
+// null.
+
+ case 'object':
+
+// Due to a specification blunder in ECMAScript, typeof null is 'object',
+// so watch out for that case.
+
+ if (!value) {
+ return 'null';
+ }
+
+// Make an array to hold the partial results of stringifying this object value.
+
+ gap += indent;
+ partial = [];
+
+// Is the value an array?
+
+ if (Object.prototype.toString.apply(value) === '[object Array]') {
+
+// The value is an array. Stringify every element. Use null as a placeholder
+// for non-JSON values.
+
+ length = value.length;
+ for (i = 0; i < length; i += 1) {
+ partial[i] = str(i, value) || 'null';
+ }
+
+// Join all of the elements together, separated with commas, and wrap them in
+// brackets.
+
+ v = partial.length === 0 ? '[]' :
+ gap ? '[\n' + gap +
+ partial.join(',\n' + gap) + '\n' +
+ mind + ']' :
+ '[' + partial.join(',') + ']';
+ gap = mind;
+ return v;
+ }
+
+// If the replacer is an array, use it to select the members to be stringified.
+
+ if (rep && typeof rep === 'object') {
+ length = rep.length;
+ for (i = 0; i < length; i += 1) {
+ k = rep[i];
+ if (typeof k === 'string') {
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ } else {
+
+// Otherwise, iterate through all of the keys in the object.
+
+ for (k in value) {
+ if (Object.hasOwnProperty.call(value, k)) {
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ }
+
+// Join all of the member texts together, separated with commas,
+// and wrap them in braces.
+
+ v = partial.length === 0 ? '{}' :
+ gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
+ mind + '}' : '{' + partial.join(',') + '}';
+ gap = mind;
+ return v;
+ }
+ }
+
+// If the JSON object does not yet have a stringify method, give it one.
+