diff --git a/node_modules/.bin/express b/node_modules/.bin/express
deleted file mode 120000
index b741d99..0000000
--- a/node_modules/.bin/express
+++ /dev/null
@@ -1 +0,0 @@
-../express/bin/express
\ No newline at end of file
diff --git a/node_modules/.bin/jade b/node_modules/.bin/jade
deleted file mode 120000
index 571fae7..0000000
--- a/node_modules/.bin/jade
+++ /dev/null
@@ -1 +0,0 @@
-../jade/bin/jade
\ No newline at end of file
diff --git a/node_modules/.bin/jshint b/node_modules/.bin/jshint
deleted file mode 120000
index fca005f..0000000
--- a/node_modules/.bin/jshint
+++ /dev/null
@@ -1 +0,0 @@
-../jshint/bin/hint
\ No newline at end of file
diff --git a/node_modules/.bin/mocha b/node_modules/.bin/mocha
deleted file mode 120000
index 43c668d..0000000
--- a/node_modules/.bin/mocha
+++ /dev/null
@@ -1 +0,0 @@
-../mocha/bin/mocha
\ No newline at end of file
diff --git a/node_modules/.bin/mocha-debug b/node_modules/.bin/mocha-debug
deleted file mode 120000
index 6564fc1..0000000
--- a/node_modules/.bin/mocha-debug
+++ /dev/null
@@ -1 +0,0 @@
-../mocha/bin/mocha-debug
\ No newline at end of file
diff --git a/node_modules/async/.gitmodules b/node_modules/async/.gitmodules
deleted file mode 100644
index a9aae98..0000000
--- a/node_modules/async/.gitmodules
+++ /dev/null
@@ -1,9 +0,0 @@
-[submodule "deps/nodeunit"]
- path = deps/nodeunit
- url = git://github.com/caolan/nodeunit.git
-[submodule "deps/UglifyJS"]
- path = deps/UglifyJS
- url = https://github.com/mishoo/UglifyJS.git
-[submodule "deps/nodelint"]
- path = deps/nodelint
- url = https://github.com/tav/nodelint.git
diff --git a/node_modules/async/LICENSE b/node_modules/async/LICENSE
deleted file mode 100644
index b7f9d50..0000000
--- a/node_modules/async/LICENSE
+++ /dev/null
@@ -1,19 +0,0 @@
-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.
diff --git a/node_modules/async/Makefile b/node_modules/async/Makefile
deleted file mode 100644
index 00f07ea..0000000
--- a/node_modules/async/Makefile
+++ /dev/null
@@ -1,21 +0,0 @@
-PACKAGE = asyncjs
-NODEJS = $(if $(shell test -f /usr/bin/nodejs && echo "true"),nodejs,node)
-
-BUILDDIR = dist
-
-all: build
-
-build: $(wildcard lib/*.js)
- mkdir -p $(BUILDDIR)
- uglifyjs lib/async.js > $(BUILDDIR)/async.min.js
-
-test:
- nodeunit test
-
-clean:
- rm -rf $(BUILDDIR)
-
-lint:
- nodelint --config nodelint.cfg lib/async.js
-
-.PHONY: test build all
diff --git a/node_modules/async/README.md b/node_modules/async/README.md
deleted file mode 100644
index f3c44ac..0000000
--- a/node_modules/async/README.md
+++ /dev/null
@@ -1,1009 +0,0 @@
-# Async.js
-
-Async is a utility module which provides straight-forward, powerful functions
-for working with asynchronous JavaScript. Although originally designed for
-use with [node.js](http://nodejs.org), it can also be used directly in the
-browser.
-
-Async provides around 20 functions that include the usual 'functional'
-suspects (map, reduce, filter, forEach…) as well as some common patterns
-for asynchronous control flow (parallel, series, waterfall…). All these
-functions assume you follow the node.js convention of providing a single
-callback as the last argument of your async function.
-
-
-## Quick Examples
-
- async.map(['file1','file2','file3'], fs.stat, function(err, results){
- // results is now an array of stats for each file
- });
-
- async.filter(['file1','file2','file3'], path.exists, function(results){
- // results now equals an array of the existing files
- });
-
- async.parallel([
- function(){ ... },
- function(){ ... }
- ], callback);
-
- async.series([
- function(){ ... },
- function(){ ... }
- ]);
-
-There are many more functions available so take a look at the docs below for a
-full list. This module aims to be comprehensive, so if you feel anything is
-missing please create a GitHub issue for it.
-
-
-## Download
-
-Releases are available for download from
-[GitHub](http://github.com/caolan/async/downloads).
-Alternatively, you can install using Node Package Manager (npm):
-
- npm install async
-
-
-__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 17.5kb Uncompressed
-
-__Production:__ [async.min.js](https://github.com/caolan/async/raw/master/dist/async.min.js) - 1.7kb Packed and Gzipped
-
-
-## In the Browser
-
-So far its been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. Usage:
-
-
-
-
-
-## Documentation
-
-### Collections
-
-* [forEach](#forEach)
-* [map](#map)
-* [filter](#filter)
-* [reject](#reject)
-* [reduce](#reduce)
-* [detect](#detect)
-* [sortBy](#sortBy)
-* [some](#some)
-* [every](#every)
-* [concat](#concat)
-
-### Control Flow
-
-* [series](#series)
-* [parallel](#parallel)
-* [whilst](#whilst)
-* [until](#until)
-* [waterfall](#waterfall)
-* [queue](#queue)
-* [auto](#auto)
-* [iterator](#iterator)
-* [apply](#apply)
-* [nextTick](#nextTick)
-
-### Utils
-
-* [memoize](#memoize)
-* [unmemoize](#unmemoize)
-* [log](#log)
-* [dir](#dir)
-* [noConflict](#noConflict)
-
-
-## Collections
-
-
-### forEach(arr, iterator, callback)
-
-Applies an iterator function to each item in an array, in parallel.
-The iterator is called with an item from the list and a callback for when it
-has finished. If the iterator passes an error to this callback, the main
-callback for the forEach function is immediately called with the error.
-
-Note, that since this function applies the iterator to each item in parallel
-there is no guarantee that the iterator functions will complete in order.
-
-__Arguments__
-
-* arr - An array to iterate over.
-* iterator(item, callback) - A function to apply to each item in the array.
- The iterator is passed a callback which must be called once it has completed.
-* callback(err) - A callback which is called after all the iterator functions
- have finished, or an error has occurred.
-
-__Example__
-
- // assuming openFiles is an array of file names and saveFile is a function
- // to save the modified contents of that file:
-
- async.forEach(openFiles, saveFile, function(err){
- // if any of the saves produced an error, err would equal that error
- });
-
----------------------------------------
-
-
-### forEachSeries(arr, iterator, callback)
-
-The same as forEach only the iterator is applied to each item in the array in
-series. The next iterator is only called once the current one has completed
-processing. This means the iterator functions will complete in order.
-
-
----------------------------------------
-
-
-### forEachLimit(arr, limit, iterator, callback)
-
-The same as forEach only the iterator is applied to batches of items in the
-array, in series. The next batch of iterators is only called once the current
-one has completed processing.
-
-__Arguments__
-
-* arr - An array to iterate over.
-* limit - How many items should be in each batch.
-* iterator(item, callback) - A function to apply to each item in the array.
- The iterator is passed a callback which must be called once it has completed.
-* callback(err) - A callback which is called after all the iterator functions
- have finished, or an error has occurred.
-
-__Example__
-
- // Assume documents is an array of JSON objects and requestApi is a
- // function that interacts with a rate-limited REST api.
-
- async.forEachLimit(documents, 20, requestApi, function(err){
- // if any of the saves produced an error, err would equal that error
- });
----------------------------------------
-
-
-### map(arr, iterator, callback)
-
-Produces a new array of values by mapping each value in the given array through
-the iterator function. The iterator is called with an item from the array and a
-callback for when it has finished processing. The callback takes 2 arguments,
-an error and the transformed item from the array. If the iterator passes an
-error to this callback, the main callback for the map function is immediately
-called with the error.
-
-Note, that since this function applies the iterator to each item in parallel
-there is no guarantee that the iterator functions will complete in order, however
-the results array will be in the same order as the original array.
-
-__Arguments__
-
-* arr - An array to iterate over.
-* iterator(item, callback) - A function to apply to each item in the array.
- The iterator is passed a callback which must be called once it has completed
- with an error (which can be null) and a transformed item.
-* callback(err, results) - A callback which is called after all the iterator
- functions have finished, or an error has occurred. Results is an array of the
- transformed items from the original array.
-
-__Example__
-
- async.map(['file1','file2','file3'], fs.stat, function(err, results){
- // results is now an array of stats for each file
- });
-
----------------------------------------
-
-
-### mapSeries(arr, iterator, callback)
-
-The same as map only the iterator is applied to each item in the array in
-series. The next iterator is only called once the current one has completed
-processing. The results array will be in the same order as the original.
-
-
----------------------------------------
-
-
-### filter(arr, iterator, callback)
-
-__Alias:__ select
-
-Returns a new array of all the values which pass an async truth test.
-_The callback for each iterator call only accepts a single argument of true or
-false, it does not accept an error argument first!_ This is in-line with the
-way node libraries work with truth tests like path.exists. This operation is
-performed in parallel, but the results array will be in the same order as the
-original.
-
-__Arguments__
-
-* arr - An array to iterate over.
-* iterator(item, callback) - A truth test to apply to each item in the array.
- The iterator is passed a callback which must be called once it has completed.
-* callback(results) - A callback which is called after all the iterator
- functions have finished.
-
-__Example__
-
- async.filter(['file1','file2','file3'], path.exists, function(results){
- // results now equals an array of the existing files
- });
-
----------------------------------------
-
-
-### filterSeries(arr, iterator, callback)
-
-__alias:__ selectSeries
-
-The same as filter only the iterator is applied to each item in the array in
-series. The next iterator is only called once the current one has completed
-processing. The results array will be in the same order as the original.
-
----------------------------------------
-
-
-### reject(arr, iterator, callback)
-
-The opposite of filter. Removes values that pass an async truth test.
-
----------------------------------------
-
-
-### rejectSeries(arr, iterator, callback)
-
-The same as filter, only the iterator is applied to each item in the array
-in series.
-
-
----------------------------------------
-
-
-### reduce(arr, memo, iterator, callback)
-
-__aliases:__ inject, foldl
-
-Reduces a list of values into a single value using an async iterator to return
-each successive step. Memo is the initial state of the reduction. This
-function only operates in series. For performance reasons, it may make sense to
-split a call to this function into a parallel map, then use the normal
-Array.prototype.reduce on the results. This function is for situations where
-each step in the reduction needs to be async, if you can get the data before
-reducing it then its probably a good idea to do so.
-
-__Arguments__
-
-* arr - An array to iterate over.
-* memo - The initial state of the reduction.
-* iterator(memo, item, callback) - A function applied to each item in the
- array to produce the next step in the reduction. The iterator is passed a
- callback which accepts an optional error as its first argument, and the state
- of the reduction as the second. If an error is passed to the callback, the
- reduction is stopped and the main callback is immediately called with the
- error.
-* callback(err, result) - A callback which is called after all the iterator
- functions have finished. Result is the reduced value.
-
-__Example__
-
- async.reduce([1,2,3], 0, function(memo, item, callback){
- // pointless async:
- process.nextTick(function(){
- callback(null, memo + item)
- });
- }, function(err, result){
- // result is now equal to the last value of memo, which is 6
- });
-
----------------------------------------
-
-
-### reduceRight(arr, memo, iterator, callback)
-
-__Alias:__ foldr
-
-Same as reduce, only operates on the items in the array in reverse order.
-
-
----------------------------------------
-
-
-### detect(arr, iterator, callback)
-
-Returns the first value in a list that passes an async truth test. The
-iterator is applied in parallel, meaning the first iterator to return true will
-fire the detect callback with that result. That means the result might not be
-the first item in the original array (in terms of order) that passes the test.
-
-If order within the original array is important then look at detectSeries.
-
-__Arguments__
-
-* arr - An array to iterate over.
-* iterator(item, callback) - A truth test to apply to each item in the array.
- The iterator is passed a callback which must be called once it has completed.
-* callback(result) - A callback which is called as soon as any iterator returns
- true, or after all the iterator functions have finished. Result will be
- the first item in the array that passes the truth test (iterator) or the
- value undefined if none passed.
-
-__Example__
-
- async.detect(['file1','file2','file3'], path.exists, function(result){
- // result now equals the first file in the list that exists
- });
-
----------------------------------------
-
-
-### detectSeries(arr, iterator, callback)
-
-The same as detect, only the iterator is applied to each item in the array
-in series. This means the result is always the first in the original array (in
-terms of array order) that passes the truth test.
-
-
----------------------------------------
-
-
-### sortBy(arr, iterator, callback)
-
-Sorts a list by the results of running each value through an async iterator.
-
-__Arguments__
-
-* arr - An array to iterate over.
-* iterator(item, callback) - A function to apply to each item in the array.
- The iterator is passed a callback which must be called once it has completed
- with an error (which can be null) and a value to use as the sort criteria.
-* callback(err, results) - A callback which is called after all the iterator
- functions have finished, or an error has occurred. Results is the items from
- the original array sorted by the values returned by the iterator calls.
-
-__Example__
-
- async.sortBy(['file1','file2','file3'], function(file, callback){
- fs.stat(file, function(err, stats){
- callback(err, stats.mtime);
- });
- }, function(err, results){
- // results is now the original array of files sorted by
- // modified date
- });
-
-
----------------------------------------
-
-
-### some(arr, iterator, callback)
-
-__Alias:__ any
-
-Returns true if at least one element in the array satisfies an async test.
-_The callback for each iterator call only accepts a single argument of true or
-false, it does not accept an error argument first!_ This is in-line with the
-way node libraries work with truth tests like path.exists. Once any iterator
-call returns true, the main callback is immediately called.
-
-__Arguments__
-
-* arr - An array to iterate over.
-* iterator(item, callback) - A truth test to apply to each item in the array.
- The iterator is passed a callback which must be called once it has completed.
-* callback(result) - A callback which is called as soon as any iterator returns
- true, or after all the iterator functions have finished. Result will be
- either true or false depending on the values of the async tests.
-
-__Example__
-
- async.some(['file1','file2','file3'], path.exists, function(result){
- // if result is true then at least one of the files exists
- });
-
----------------------------------------
-
-
-### every(arr, iterator, callback)
-
-__Alias:__ all
-
-Returns true if every element in the array satisfies an async test.
-_The callback for each iterator call only accepts a single argument of true or
-false, it does not accept an error argument first!_ This is in-line with the
-way node libraries work with truth tests like path.exists.
-
-__Arguments__
-
-* arr - An array to iterate over.
-* iterator(item, callback) - A truth test to apply to each item in the array.
- The iterator is passed a callback which must be called once it has completed.
-* callback(result) - A callback which is called after all the iterator
- functions have finished. Result will be either true or false depending on
- the values of the async tests.
-
-__Example__
-
- async.every(['file1','file2','file3'], path.exists, function(result){
- // if result is true then every file exists
- });
-
----------------------------------------
-
-
-### concat(arr, iterator, callback)
-
-Applies an iterator to each item in a list, concatenating the results. Returns the
-concatenated list. The iterators are called in parallel, and the results are
-concatenated as they return. There is no guarantee that the results array will
-be returned in the original order of the arguments passed to the iterator function.
-
-__Arguments__
-
-* arr - An array to iterate over
-* iterator(item, callback) - A function to apply to each item in the array.
- The iterator is passed a callback which must be called once it has completed
- with an error (which can be null) and an array of results.
-* callback(err, results) - A callback which is called after all the iterator
- functions have finished, or an error has occurred. Results is an array containing
- the concatenated results of the iterator function.
-
-__Example__
-
- async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){
- // files is now a list of filenames that exist in the 3 directories
- });
-
----------------------------------------
-
-
-### concatSeries(arr, iterator, callback)
-
-Same as async.concat, but executes in series instead of parallel.
-
-
-## Control Flow
-
-
-### series(tasks, [callback])
-
-Run an array of functions in series, each one running once the previous
-function has completed. If any functions in the series pass an error to its
-callback, no more functions are run and the callback for the series is
-immediately called with the value of the error. Once the tasks have completed,
-the results are passed to the final callback as an array.
-
-It is also possible to use an object instead of an array. Each property will be
-run as a function and the results will be passed to the final callback as an object
-instead of an array. This can be a more readable way of handling results from
-async.series.
-
-
-__Arguments__
-
-* tasks - An array or object containing functions to run, each function is passed
- a callback it must call on completion.
-* callback(err, results) - An optional callback to run once all the functions
- have completed. This function gets an array of all the arguments passed to
- the callbacks used in the array.
-
-__Example__
-
- async.series([
- function(callback){
- // do some stuff ...
- callback(null, 'one');
- },
- function(callback){
- // do some more stuff ...
- callback(null, 'two');
- },
- ],
- // optional callback
- function(err, results){
- // results is now equal to ['one', 'two']
- });
-
-
- // an example using an object instead of an array
- async.series({
- one: function(callback){
- setTimeout(function(){
- callback(null, 1);
- }, 200);
- },
- two: function(callback){
- setTimeout(function(){
- callback(null, 2);
- }, 100);
- },
- },
- function(err, results) {
- // results is now equal to: {one: 1, two: 2}
- });
-
-
----------------------------------------
-
-
-### parallel(tasks, [callback])
-
-Run an array of functions in parallel, without waiting until the previous
-function has completed. If any of the functions pass an error to its
-callback, the main callback is immediately called with the value of the error.
-Once the tasks have completed, the results are passed to the final callback as an
-array.
-
-It is also possible to use an object instead of an array. Each property will be
-run as a function and the results will be passed to the final callback as an object
-instead of an array. This can be a more readable way of handling results from
-async.parallel.
-
-
-__Arguments__
-
-* tasks - An array or object containing functions to run, each function is passed a
- callback it must call on completion.
-* callback(err, results) - An optional callback to run once all the functions
- have completed. This function gets an array of all the arguments passed to
- the callbacks used in the array.
-
-__Example__
-
- async.parallel([
- function(callback){
- setTimeout(function(){
- callback(null, 'one');
- }, 200);
- },
- function(callback){
- setTimeout(function(){
- callback(null, 'two');
- }, 100);
- },
- ],
- // optional callback
- function(err, results){
- // in this case, the results array will equal ['two','one']
- // because the functions were run in parallel and the second
- // function had a shorter timeout before calling the callback.
- });
-
-
- // an example using an object instead of an array
- async.parallel({
- one: function(callback){
- setTimeout(function(){
- callback(null, 1);
- }, 200);
- },
- two: function(callback){
- setTimeout(function(){
- callback(null, 2);
- }, 100);
- },
- },
- function(err, results) {
- // results is now equals to: {one: 1, two: 2}
- });
-
-
----------------------------------------
-
-
-### whilst(test, fn, callback)
-
-Repeatedly call fn, while test returns true. Calls the callback when stopped,
-or an error occurs.
-
-__Arguments__
-
-* test() - synchronous truth test to perform before each execution of fn.
-* fn(callback) - A function to call each time the test passes. The function is
- passed a callback which must be called once it has completed with an optional
- error as the first argument.
-* callback(err) - A callback which is called after the test fails and repeated
- execution of fn has stopped.
-
-__Example__
-
- var count = 0;
-
- async.whilst(
- function () { return count < 5; },
- function (callback) {
- count++;
- setTimeout(callback, 1000);
- },
- function (err) {
- // 5 seconds have passed
- }
- });
-
-
----------------------------------------
-
-
-### until(test, fn, callback)
-
-Repeatedly call fn, until test returns true. Calls the callback when stopped,
-or an error occurs.
-
-The inverse of async.whilst.
-
-
----------------------------------------
-
-
-### waterfall(tasks, [callback])
-
-Runs an array of functions in series, each passing their results to the next in
-the array. However, if any of the functions pass an error to the callback, the
-next function is not executed and the main callback is immediately called with
-the error.
-
-__Arguments__
-
-* tasks - An array of functions to run, each function is passed a callback it
- must call on completion.
-* callback(err) - An optional callback to run once all the functions have
- completed. This function gets passed any error that may have occurred.
-
-__Example__
-
- async.waterfall([
- function(callback){
- callback(null, 'one', 'two');
- },
- function(arg1, arg2, callback){
- callback(null, 'three');
- },
- function(arg1, callback){
- // arg1 now equals 'three'
- callback(null, 'done');
- }
- ]);
-
-
----------------------------------------
-
-
-### queue(worker, concurrency)
-
-Creates a queue object with the specified concurrency. Tasks added to the
-queue will be processed in parallel (up to the concurrency limit). If all
-workers are in progress, the task is queued until one is available. Once
-a worker has completed a task, the task's callback is called.
-
-__Arguments__
-
-* worker(task, callback) - An asynchronous function for processing a queued
- task.
-* concurrency - An integer for determining how many worker functions should be
- run in parallel.
-
-__Queue objects__
-
-The queue object returned by this function has the following properties and
-methods:
-
-* length() - a function returning the number of items waiting to be processed.
-* concurrency - an integer for determining how many worker functions should be
- run in parallel. This property can be changed after a queue is created to
- alter the concurrency on-the-fly.
-* push(task, [callback]) - add a new task to the queue, the callback is called
- once the worker has finished processing the task.
-* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued
-* empty - a callback that is called when the last item from the queue is given to a worker
-* drain - a callback that is called when the last item from the queue has returned from the worker
-
-__Example__
-
- // create a queue object with concurrency 2
-
- var q = async.queue(function (task, callback) {
- console.log('hello ' + task.name);
- callback();
- }, 2);
-
-
- // assign a callback
- q.drain = function() {
- console.log('all items have been processed');
- }
-
- // add some items to the queue
-
- q.push({name: 'foo'}, function (err) {
- console.log('finished processing foo');
- });
- q.push({name: 'bar'}, function (err) {
- console.log('finished processing bar');
- });
-
-
----------------------------------------
-
-
-### auto(tasks, [callback])
-
-Determines the best order for running functions based on their requirements.
-Each function can optionally depend on other functions being completed first,
-and each function is run as soon as its requirements are satisfied. If any of
-the functions pass an error to their callback, that function will not complete
-(so any other functions depending on it will not run) and the main callback
-will be called immediately with the error. Functions also receive an object
-containing the results of functions on which they depend.
-
-__Arguments__
-
-* tasks - An object literal containing named functions or an array of
- requirements, with the function itself the last item in the array. The key
- used for each function or array is used when specifying requirements. The
- syntax is easier to understand by looking at the example.
-* callback(err) - An optional callback which is called when all the tasks have
- been completed. The callback may receive an error as an argument.
-
-__Example__
-
- async.auto({
- get_data: function(callback){
- // async code to get some data
- },
- make_folder: function(callback){
- // async code to create a directory to store a file in
- // this is run at the same time as getting the data
- },
- write_file: ['get_data', 'make_folder', function(callback){
- // once there is some data and the directory exists,
- // write the data to a file in the directory
- callback(null, filename);
- }],
- email_link: ['write_file', function(callback, results){
- // once the file is written let's email a link to it...
- // results.write_file contains the filename returned by write_file.
- }]
- });
-
-This is a fairly trivial example, but to do this using the basic parallel and
-series functions would look like this:
-
- async.parallel([
- function(callback){
- // async code to get some data
- },
- function(callback){
- // async code to create a directory to store a file in
- // this is run at the same time as getting the data
- }
- ],
- function(results){
- async.series([
- function(callback){
- // once there is some data and the directory exists,
- // write the data to a file in the directory
- },
- email_link: ['write_file', function(callback){
- // once the file is written let's email a link to it...
- }
- ]);
- });
-
-For a complicated series of async tasks using the auto function makes adding
-new tasks much easier and makes the code more readable.
-
-
----------------------------------------
-
-
-### iterator(tasks)
-
-Creates an iterator function which calls the next function in the array,
-returning a continuation to call the next one after that. Its also possible to
-'peek' the next iterator by doing iterator.next().
-
-This function is used internally by the async module but can be useful when
-you want to manually control the flow of functions in series.
-
-__Arguments__
-
-* tasks - An array of functions to run, each function is passed a callback it
- must call on completion.
-
-__Example__
-
- var iterator = async.iterator([
- function(){ sys.p('one'); },
- function(){ sys.p('two'); },
- function(){ sys.p('three'); }
- ]);
-
- node> var iterator2 = iterator();
- 'one'
- node> var iterator3 = iterator2();
- 'two'
- node> iterator3();
- 'three'
- node> var nextfn = iterator2.next();
- node> nextfn();
- 'three'
-
-
----------------------------------------
-
-
-### apply(function, arguments..)
-
-Creates a continuation function with some arguments already applied, a useful
-shorthand when combined with other control flow functions. Any arguments
-passed to the returned function are added to the arguments originally passed
-to apply.
-
-__Arguments__
-
-* function - The function you want to eventually apply all arguments to.
-* arguments... - Any number of arguments to automatically apply when the
- continuation is called.
-
-__Example__
-
- // using apply
-
- async.parallel([
- async.apply(fs.writeFile, 'testfile1', 'test1'),
- async.apply(fs.writeFile, 'testfile2', 'test2'),
- ]);
-
-
- // the same process without using apply
-
- async.parallel([
- function(callback){
- fs.writeFile('testfile1', 'test1', callback);
- },
- function(callback){
- fs.writeFile('testfile2', 'test2', callback);
- },
- ]);
-
-It's possible to pass any number of additional arguments when calling the
-continuation:
-
- node> var fn = async.apply(sys.puts, 'one');
- node> fn('two', 'three');
- one
- two
- three
-
----------------------------------------
-
-
-### nextTick(callback)
-
-Calls the callback on a later loop around the event loop. In node.js this just
-calls process.nextTick, in the browser it falls back to setTimeout(callback, 0),
-which means other higher priority events may precede the execution of the callback.
-
-This is used internally for browser-compatibility purposes.
-
-__Arguments__
-
-* callback - The function to call on a later loop around the event loop.
-
-__Example__
-
- var call_order = [];
- async.nextTick(function(){
- call_order.push('two');
- // call_order now equals ['one','two]
- });
- call_order.push('one')
-
-
-## Utils
-
-
-### memoize(fn, [hasher])
-
-Caches the results of an async function. When creating a hash to store function
-results against, the callback is omitted from the hash and an optional hash
-function can be used.
-
-__Arguments__
-
-* fn - the function you to proxy and cache results from.
-* hasher - an optional function for generating a custom hash for storing
- results, it has all the arguments applied to it apart from the callback, and
- must be synchronous.
-
-__Example__
-
- var slow_fn = function (name, callback) {
- // do something
- callback(null, result);
- };
- var fn = async.memoize(slow_fn);
-
- // fn can now be used as if it were slow_fn
- fn('some name', function () {
- // callback
- });
-
-
-### unmemoize(fn)
-
-Undoes a memoized function, reverting it to the original, unmemoized
-form. Comes handy in tests.
-
-__Arguments__
-
-* fn - the memoized function
-
-
-### log(function, arguments)
-
-Logs the result of an async function to the console. Only works in node.js or
-in browsers that support console.log and console.error (such as FF and Chrome).
-If multiple arguments are returned from the async function, console.log is
-called on each argument in order.
-
-__Arguments__
-
-* function - The function you want to eventually apply all arguments to.
-* arguments... - Any number of arguments to apply to the function.
-
-__Example__
-
- var hello = function(name, callback){
- setTimeout(function(){
- callback(null, 'hello ' + name);
- }, 1000);
- };
-
- node> async.log(hello, 'world');
- 'hello world'
-
-
----------------------------------------
-
-
-### dir(function, arguments)
-
-Logs the result of an async function to the console using console.dir to
-display the properties of the resulting object. Only works in node.js or
-in browsers that support console.dir and console.error (such as FF and Chrome).
-If multiple arguments are returned from the async function, console.dir is
-called on each argument in order.
-
-__Arguments__
-
-* function - The function you want to eventually apply all arguments to.
-* arguments... - Any number of arguments to apply to the function.
-
-__Example__
-
- var hello = function(name, callback){
- setTimeout(function(){
- callback(null, {hello: name});
- }, 1000);
- };
-
- node> async.dir(hello, 'world');
- {hello: 'world'}
-
-
----------------------------------------
-
-
-### noConflict()
-
-Changes the value of async back to its original value, returning a reference to the
-async object.
diff --git a/node_modules/async/deps/nodeunit.css b/node_modules/async/deps/nodeunit.css
deleted file mode 100644
index 274434a..0000000
--- a/node_modules/async/deps/nodeunit.css
+++ /dev/null
@@ -1,70 +0,0 @@
-/*!
- * Styles taken from qunit.css
- */
-
-h1#nodeunit-header, h1.nodeunit-header {
- padding: 15px;
- font-size: large;
- background-color: #06b;
- color: white;
- font-family: 'trebuchet ms', verdana, arial;
- margin: 0;
-}
-
-h1#nodeunit-header a {
- color: white;
-}
-
-h2#nodeunit-banner {
- height: 2em;
- border-bottom: 1px solid white;
- background-color: #eee;
- margin: 0;
- font-family: 'trebuchet ms', verdana, arial;
-}
-h2#nodeunit-banner.pass {
- background-color: green;
-}
-h2#nodeunit-banner.fail {
- background-color: red;
-}
-
-h2#nodeunit-userAgent, h2.nodeunit-userAgent {
- padding: 10px;
- background-color: #eee;
- color: black;
- margin: 0;
- font-size: small;
- font-weight: normal;
- font-family: 'trebuchet ms', verdana, arial;
- font-size: 10pt;
-}
-
-div#nodeunit-testrunner-toolbar {
- background: #eee;
- border-top: 1px solid black;
- padding: 10px;
- font-family: 'trebuchet ms', verdana, arial;
- margin: 0;
- font-size: 10pt;
-}
-
-ol#nodeunit-tests {
- font-family: 'trebuchet ms', verdana, arial;
- font-size: 10pt;
-}
-ol#nodeunit-tests li strong {
- cursor:pointer;
-}
-ol#nodeunit-tests .pass {
- color: green;
-}
-ol#nodeunit-tests .fail {
- color: red;
-}
-
-p#nodeunit-testresult {
- margin-left: 1em;
- font-size: 10pt;
- font-family: 'trebuchet ms', verdana, arial;
-}
diff --git a/node_modules/async/deps/nodeunit.js b/node_modules/async/deps/nodeunit.js
deleted file mode 100644
index 5957184..0000000
--- a/node_modules/async/deps/nodeunit.js
+++ /dev/null
@@ -1,1966 +0,0 @@
-/*!
- * 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 ' '),
- 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');
- };
- }
-}());
-var assert = this.assert = {};
-var types = {};
-var core = {};
-var nodeunit = {};
-var reporter = {};
-/*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 ////
- async.nextTick = function (fn) {
- if (typeof process === 'undefined' || !(process.nextTick)) {
- setTimeout(fn, 0);
- }
- else {
- process.nextTick(fn);
- }
- };
-
- 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');*/
-
-}());
-(function(exports){
-/**
- * This file is based on the node.js assert module, but with some small
- * changes for browser-compatibility
- * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS!
- */
-
-
-/**
- * Added for browser compatibility
- */
-
-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;
-};
-
-
-
-// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
-//
-// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
-//
-// Originally from narwhal.js (http://narwhaljs.org)
-// Copyright (c) 2009 Thomas Robinson <280north.com>
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the 'Software'), to
-// deal in the Software without restriction, including without limitation the
-// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-// sell copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS 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.
-
-
-var pSlice = Array.prototype.slice;
-
-// 1. The assert module provides functions that throw
-// AssertionError's when particular conditions are not met. The
-// assert module must conform to the following interface.
-
-var assert = exports;
-
-// 2. The AssertionError is defined in assert.
-// new assert.AssertionError({message: message, actual: actual, expected: expected})
-
-assert.AssertionError = function AssertionError (options) {
- this.name = "AssertionError";
- this.message = options.message;
- this.actual = options.actual;
- this.expected = options.expected;
- this.operator = options.operator;
- var stackStartFunction = options.stackStartFunction || fail;
-
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, stackStartFunction);
- }
-};
-// code from util.inherits in node
-assert.AssertionError.super_ = Error;
-
-
-// EDITED FOR BROWSER COMPATIBILITY: replaced Object.create call
-// TODO: test what effect this may have
-var ctor = function () { this.constructor = assert.AssertionError; };
-ctor.prototype = Error.prototype;
-assert.AssertionError.prototype = new ctor();
-
-
-assert.AssertionError.prototype.toString = function() {
- if (this.message) {
- return [this.name+":", this.message].join(' ');
- } else {
- return [ this.name+":"
- , JSON.stringify(this.expected )
- , this.operator
- , JSON.stringify(this.actual)
- ].join(" ");
- }
-};
-
-// assert.AssertionError instanceof Error
-
-assert.AssertionError.__proto__ = Error.prototype;
-
-// At present only the three keys mentioned above are used and
-// understood by the spec. Implementations or sub modules can pass
-// other keys to the AssertionError's constructor - they will be
-// ignored.
-
-// 3. All of the following functions must throw an AssertionError
-// when a corresponding condition is not met, with a message that
-// may be undefined if not provided. All assertion methods provide
-// both the actual and expected values to the assertion error for
-// display purposes.
-
-function fail(actual, expected, message, operator, stackStartFunction) {
- throw new assert.AssertionError({
- message: message,
- actual: actual,
- expected: expected,
- operator: operator,
- stackStartFunction: stackStartFunction
- });
-}
-
-// EXTENSION! allows for well behaved errors defined elsewhere.
-assert.fail = fail;
-
-// 4. Pure assertion tests whether a value is truthy, as determined
-// by !!guard.
-// assert.ok(guard, message_opt);
-// This statement is equivalent to assert.equal(true, guard,
-// message_opt);. To test strictly for the value true, use
-// assert.strictEqual(true, guard, message_opt);.
-
-assert.ok = function ok(value, message) {
- if (!!!value) fail(value, true, message, "==", assert.ok);
-};
-
-// 5. The equality assertion tests shallow, coercive equality with
-// ==.
-// assert.equal(actual, expected, message_opt);
-
-assert.equal = function equal(actual, expected, message) {
- if (actual != expected) fail(actual, expected, message, "==", assert.equal);
-};
-
-// 6. The non-equality assertion tests for whether two objects are not equal
-// with != assert.notEqual(actual, expected, message_opt);
-
-assert.notEqual = function notEqual(actual, expected, message) {
- if (actual == expected) {
- fail(actual, expected, message, "!=", assert.notEqual);
- }
-};
-
-// 7. The equivalence assertion tests a deep equality relation.
-// assert.deepEqual(actual, expected, message_opt);
-
-assert.deepEqual = function deepEqual(actual, expected, message) {
- if (!_deepEqual(actual, expected)) {
- fail(actual, expected, message, "deepEqual", assert.deepEqual);
- }
-};
-
-function _deepEqual(actual, expected) {
- // 7.1. All identical values are equivalent, as determined by ===.
- if (actual === expected) {
- return true;
- // 7.2. If the expected value is a Date object, the actual value is
- // equivalent if it is also a Date object that refers to the same time.
- } else if (actual instanceof Date && expected instanceof Date) {
- return actual.getTime() === expected.getTime();
-
- // 7.3. Other pairs that do not both pass typeof value == "object",
- // equivalence is determined by ==.
- } else if (typeof actual != 'object' && typeof expected != 'object') {
- return actual == expected;
-
- // 7.4. For all other Object pairs, including Array objects, equivalence is
- // determined by having the same number of owned properties (as verified
- // with Object.prototype.hasOwnProperty.call), the same set of keys
- // (although not necessarily the same order), equivalent values for every
- // corresponding key, and an identical "prototype" property. Note: this
- // accounts for both named and indexed properties on Arrays.
- } else {
- return objEquiv(actual, expected);
- }
-}
-
-function isUndefinedOrNull (value) {
- return value === null || value === undefined;
-}
-
-function isArguments (object) {
- return Object.prototype.toString.call(object) == '[object Arguments]';
-}
-
-function objEquiv (a, b) {
- if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
- return false;
- // an identical "prototype" property.
- if (a.prototype !== b.prototype) return false;
- //~~~I've managed to break Object.keys through screwy arguments passing.
- // Converting to array solves the problem.
- if (isArguments(a)) {
- if (!isArguments(b)) {
- return false;
- }
- a = pSlice.call(a);
- b = pSlice.call(b);
- return _deepEqual(a, b);
- }
- try{
- var ka = _keys(a),
- kb = _keys(b),
- key, i;
- } catch (e) {//happens when one is a string literal and the other isn't
- return false;
- }
- // having the same number of owned properties (keys incorporates hasOwnProperty)
- if (ka.length != kb.length)
- return false;
- //the same set of keys (although not necessarily the same order),
- ka.sort();
- kb.sort();
- //~~~cheap key test
- for (i = ka.length - 1; i >= 0; i--) {
- if (ka[i] != kb[i])
- return false;
- }
- //equivalent values for every corresponding key, and
- //~~~possibly expensive deep test
- for (i = ka.length - 1; i >= 0; i--) {
- key = ka[i];
- if (!_deepEqual(a[key], b[key] ))
- return false;
- }
- return true;
-}
-
-// 8. The non-equivalence assertion tests for any deep inequality.
-// assert.notDeepEqual(actual, expected, message_opt);
-
-assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
- if (_deepEqual(actual, expected)) {
- fail(actual, expected, message, "notDeepEqual", assert.notDeepEqual);
- }
-};
-
-// 9. The strict equality assertion tests strict equality, as determined by ===.
-// assert.strictEqual(actual, expected, message_opt);
-
-assert.strictEqual = function strictEqual(actual, expected, message) {
- if (actual !== expected) {
- fail(actual, expected, message, "===", assert.strictEqual);
- }
-};
-
-// 10. The strict non-equality assertion tests for strict inequality, as determined by !==.
-// assert.notStrictEqual(actual, expected, message_opt);
-
-assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
- if (actual === expected) {
- fail(actual, expected, message, "!==", assert.notStrictEqual);
- }
-};
-
-function _throws (shouldThrow, block, err, message) {
- var exception = null,
- threw = false,
- typematters = true;
-
- message = message || "";
-
- //handle optional arguments
- if (arguments.length == 3) {
- if (typeof(err) == "string") {
- message = err;
- typematters = false;
- }
- } else if (arguments.length == 2) {
- typematters = false;
- }
-
- try {
- block();
- } catch (e) {
- threw = true;
- exception = e;
- }
-
- if (shouldThrow && !threw) {
- fail( "Missing expected exception"
- + (err && err.name ? " ("+err.name+")." : '.')
- + (message ? " " + message : "")
- );
- }
- if (!shouldThrow && threw && typematters && exception instanceof err) {
- fail( "Got unwanted exception"
- + (err && err.name ? " ("+err.name+")." : '.')
- + (message ? " " + message : "")
- );
- }
- if ((shouldThrow && threw && typematters && !(exception instanceof err)) ||
- (!shouldThrow && threw)) {
- throw exception;
- }
-};
-
-// 11. Expected to throw an error:
-// assert.throws(block, Error_opt, message_opt);
-
-assert.throws = function(block, /*optional*/error, /*optional*/message) {
- _throws.apply(this, [true].concat(pSlice.call(arguments)));
-};
-
-// EXTENSION! This is annoying to write outside this module.
-assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
- _throws.apply(this, [false].concat(pSlice.call(arguments)));
-};
-
-assert.ifError = function (err) { if (err) {throw err;}};
-})(assert);
-(function(exports){
-/*!
- * Nodeunit
- * Copyright (c) 2010 Caolan McMahon
- * MIT Licensed
- *
- * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS!
- * Only code on that line will be removed, its mostly to avoid requiring code
- * that is node specific
- */
-
-/**
- * Module dependencies
- */
-
-
-
-/**
- * Creates assertion objects representing the result of an assert call.
- * Accepts an object or AssertionError as its argument.
- *
- * @param {object} obj
- * @api public
- */
-
-exports.assertion = function (obj) {
- return {
- method: obj.method || '',
- message: obj.message || (obj.error && obj.error.message) || '',
- error: obj.error,
- passed: function () {
- return !this.error;
- },
- failed: function () {
- return Boolean(this.error);
- }
- };
-};
-
-/**
- * Creates an assertion list object representing a group of assertions.
- * Accepts an array of assertion objects.
- *
- * @param {Array} arr
- * @param {Number} duration
- * @api public
- */
-
-exports.assertionList = function (arr, duration) {
- var that = arr || [];
- that.failures = function () {
- var failures = 0;
- for (var i=0; i Welcome to <%= title %> some html ' + http.STATUS_CODES[status] + '. Redirecting to ' + url + ' views: ' + sess.views + ' expires in: ' + (sess.cookie.maxAge / 1000) + 's
' +
- assertions.passes() + ' assertions of ' +
- '' + assertions.length + ' passed, ' +
- assertions.failures() + ' failed.';
- }
- });
-};
-})(reporter);
-nodeunit = core;
-nodeunit.assert = assert;
-nodeunit.reporter = reporter;
-nodeunit.run = reporter.run;
-return nodeunit; })();
diff --git a/node_modules/async/dist/async.min.js b/node_modules/async/dist/async.min.js
deleted file mode 100644
index e4c898b..0000000
--- a/node_modules/async/dist/async.min.js
+++ /dev/null
@@ -1 +0,0 @@
-/*global setTimeout: false, console: false */(function(){var a={},b=this,c=b.async;typeof module!="undefined"&&module.exports?module.exports=a:b.async=a,a.noConflict=function(){return b.async=c,a};var d=function(a,b){if(a.forEach)return a.forEach(b);for(var c=0;cAsync.js Test Suite
-
-
-
diff --git a/node_modules/connection_pool/.npmignore b/node_modules/connection_pool/.npmignore
deleted file mode 100644
index a4df376..0000000
--- a/node_modules/connection_pool/.npmignore
+++ /dev/null
@@ -1,3 +0,0 @@
-npm-debug.log
-*.log
-node_modules/**
\ No newline at end of file
diff --git a/node_modules/connection_pool/Readme.md b/node_modules/connection_pool/Readme.md
deleted file mode 100644
index 565d0f1..0000000
--- a/node_modules/connection_pool/Readme.md
+++ /dev/null
@@ -1,69 +0,0 @@
-Connection Pool
-================
-
-This provides a simple connection pool for node.js applications to use for managing connections to servers.
-
-It is used in [redis-proxy](https://github.com/sreeix/redis-proxy) for pooling redis connections.
-
-
-It does not LRU or release stale connections.
-
-That may be something we can build in, but right now the API expects connections to be taken and released correctly, otherwise we will end up with unused connections
-
-The API is very simple currently and is used as following
-
-
-Creation
----------
-
-`var Pool = require('connection_pool')`
-
-` var p = new Pool({maxSize: 100, delayCreation:false, growBy: 2})`
-
-Following options are available:
-
-`create` : takes a function that invokes a callback (err, conn) . This is _Mandatory_
-
-maxSize`` : Maximum connections on the pool : default 20
-
-startSize : stars with these many connections: default 1/3 of max connections(6 if not maxSize is not specified)
-
-growBy : how to grow the pool default to 1/3 of max connections
-
-delayCreation: Create only on use rather than preemptively. This may mean a slight initial pool creation expense.
-
-close : optional close function to be called after release for doing cleanups
-
-
-Taking Connections
-------------------
-
-`p.take('some_identifier', function(err, connection){
- doSomething();
-})`
-
-
-Releasing Connections
----------------------
-
-`p.close(identifier)`
-
-or
-
-`p.closeAll()`
-
-or
-
-`p.release(connection)`
-
-
-Stats
---------
-
-It exposes the following basic information
-
-`totalConnections` : The current total connections in the pool. Note that this may not be the maxSize, because the pool size may be grown later
-
-`totalFreeConnections` : show how many more connections are available in the pool
-
-`totalInUseConnections` Show the total connections currently being used.
\ No newline at end of file
diff --git a/node_modules/connection_pool/lib/connection_pool.js b/node_modules/connection_pool/lib/connection_pool.js
deleted file mode 100644
index 3297a87..0000000
--- a/node_modules/connection_pool/lib/connection_pool.js
+++ /dev/null
@@ -1,156 +0,0 @@
-var _ = require('underscore');
-var async = require('async');
-var logger = require('winston');
-var util = require('util');
-
-// maxSize : Maximum connections on the pool : default 20
-// startSize : stars with these many connections: default 1/3 of max connections(6 if not maxSize is not specified)
-// Mandatory create function -> takes a function that invokes a callback (err, conn)
-// growBy : how to grwo the pool default to 1/3 of max connections
-// delayCreation: Create only on use rather than preemptively. This may mean a slight initial poool creation expense.
-// close :
-
-var ConnectionPool = module.exports = function(o){
- var self = this;
- this.options = {maxSize: 20, close: function(cnnx){}};
- this.freepool = [];
- this.inUsePool = {};
-
- _.extend(this.options, o);
- if(!this.options.startSize){
- this.options.startSize = parseInt(this.options.maxSize/3, 10);
- if(this.options.startSize === 0) {
- this.options.startSize = this.options.maxSize;
- }
- }
- if(!this.options.growBy){
- this.options.growBy = parseInt(this.options.maxSize/3, 10);
- if(this.options.growBy === 0) {
- this.options.growBy = this.options.maxSize;
- }
- }
- if(!this.options.delayCreation){
- this._addConnectionsToPool();
- }
-};
-
-ConnectionPool.prototype.take = function take(id, cb){
- var self = this;
- if(this.inUsePool[id]){
- return cb(null, this.inUsePool[id]);
- }
- if(this.freepool.length === 0){
- this._addConnectionsToPool(function(err, done){
- if(err){
- logger.error(err);
- return cb(err);
- }
- logger.debug('Adding more to free pool and allocating.');
-
- self.inUsePool[id] = self.freepool.shift();
- return cb(null, self.inUsePool[id]);
- });
- } else {
- logger.debug('Free pool exists... reserving one from there..');
- this.inUsePool[id] = this.freepool.shift();
- return cb(null, this.inUsePool[id]);
- }
-};
-
-ConnectionPool.prototype.release = function release(conn){
- logger.debug('releaseing' + conn);
- var matchingId = null;
-
- _.each(this.inUsePool, function(x, y){
- if(_.isEqual(x, conn)){
- matchingId = y;
- }
- });
-
- if(matchingId){
- this.close(matchingId);
- }
-};
-
-ConnectionPool.prototype.close = function close(id){
- logger.debug("Releaseing "+ id);
- logger.debug(util.inspect(this.inUsePool));
- if(!_.isNull(this.inUsePool[id])){
- logger.debug('connection for id '+ id +' closed')
- this.freepool.push(this.inUsePool[id]);
- delete this.inUsePool[id];
- } else {
- logger.debug('No connection found in the pool.');
-
- }
-};
-
-ConnectionPool.prototype.closeAll = function(){
- var self = this;
- _.each(_.keys(this.inUsePool), function(id){
- self.close(id);
- });
-};
-
-Object.defineProperty(ConnectionPool.prototype, 'totalConnections', {
- get: function() {
- return this.freepool.length + _.size(this.inUsePool);
- }
-});
-
-Object.defineProperty(ConnectionPool.prototype, 'totalFreeConnections', {
- get: function() {
- return this.freepool.length;
- }
-});
-
-Object.defineProperty(ConnectionPool.prototype, 'totalInUseConnections', {
- get: function() {
- return _.size(this.inUsePool);
- }
-});
-
-
-ConnectionPool.prototype._addToFreePool = function(cb){
- var self = this, remaining;
- var howManyConnections = this.options.growBy;
- howManyConnections = (this.totalConnections === 0) ? this.options.startSize : this.options.growBy ;
-
- if(!_.isFunction(self.options.create)){
- cb('Need a create method for creating the pool connection');
- }
-
- remaining = this.options.maxSize - this.totalConnections;
- if( howManyConnections > remaining){
- howManyConnections = remaining;
- }
-
- if(remaining === 0){
- cb('Out of connections');
- }
-
- _.times(howManyConnections, function(i) {
- self.options.create(function(err, conn){
- if(err) {
- return cb(err);
- }
- self.freepool.push(conn);
- if(i+1 === howManyConnections){
- return cb(null, true);
- }
- });
- });
-};
-
-ConnectionPool.prototype._addConnectionsToPool = function(cb){
- var self = this;
- if(!cb){
- cb = function(err, conn){}
- }
- this._addToFreePool(function(err, res){
- if(err){
- return cb(err);
- }
- return cb(null, true);
- });
-};
\ No newline at end of file
diff --git a/node_modules/connection_pool/package.json b/node_modules/connection_pool/package.json
deleted file mode 100644
index 3d82f13..0000000
--- a/node_modules/connection_pool/package.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "author": "Sreekanth <%= title %>
'
- , '' + files.map(function(file){
- var icon = ''
- , classes = [];
-
- if (useIcons && '..' != file) {
- icon = icons[extname(file)] || icons.default;
- icon = '';
- classes.push('icon');
- }
-
- return '
';
-}
-
-/**
- * Load and cache the given `icon`.
- *
- * @param {String} icon
- * @return {String}
- * @api private
- */
-
-function load(icon) {
- if (cache[icon]) return cache[icon];
- return cache[icon] = fs.readFileSync(__dirname + '/../public/icons/' + icon, 'base64');
-}
-
-/**
- * Filter "hidden" `files`, aka files
- * beginning with a `.`.
- *
- * @param {Array} files
- * @return {Array}
- * @api private
- */
-
-function removeHidden(files) {
- return files.filter(function(file){
- return '.' != file[0];
- });
-}
-
-/**
- * Icon map.
- */
-
-var icons = {
- '.js': 'page_white_code_red.png'
- , '.c': 'page_white_c.png'
- , '.h': 'page_white_h.png'
- , '.cc': 'page_white_cplusplus.png'
- , '.php': 'page_white_php.png'
- , '.rb': 'page_white_ruby.png'
- , '.cpp': 'page_white_cplusplus.png'
- , '.swf': 'page_white_flash.png'
- , '.pdf': 'page_white_acrobat.png'
- , 'default': 'page_white.png'
-};
diff --git a/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js b/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js
deleted file mode 100644
index f2fc44f..0000000
--- a/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js
+++ /dev/null
@@ -1,100 +0,0 @@
-/*!
- * Connect - errorHandler
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var utils = require('../utils')
- , url = require('url')
- , fs = require('fs');
-
-/**
- * Flexible error handler, providing (_optional_) stack traces
- * and error message responses for requests accepting text, html,
- * or json.
- *
- * Options:
- *
- * - `showStack`, `stack` respond with both the error message and stack trace. Defaults to `false`
- * - `showMessage`, `message`, respond with the exception message only. Defaults to `false`
- * - `dumpExceptions`, `dump`, dump exceptions to stderr (without terminating the process). Defaults to `false`
- *
- * 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.
- *
- * @param {Object} options
- * @return {Function}
- * @api public
- */
-
-exports = module.exports = function errorHandler(options){
- options = options || {};
-
- // defaults
- var showStack = options.showStack || options.stack
- , showMessage = options.showMessage || options.message
- , dumpExceptions = options.dumpExceptions || options.dump
- , formatUrl = options.formatUrl;
-
- return function errorHandler(err, req, res, next){
- res.statusCode = 500;
- if (dumpExceptions) console.error(err.stack);
- if (showStack) {
- 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 '{linked-path}
- {files}
- {title}
- 500 {error}
- {stack}
-
foo
-bar
- -Jade also supports unbuffered comments, by simply adding a hyphen: - - //- will not output within markup - p foo - p bar - -outputting - -foo
-bar
- -### Block Comments - - A block comment is legal as well: - - body - // - #content - h1 Example - -outputting - - - - - -Jade supports conditional-comments as well, for example: - - head - //if lt IE 8 - script(src='/ie-sucks.js') - -outputs: - - - - - - -### Nesting - - Jade supports nesting to define the tags in a natural way: - - ul - li.first - a(href='#') foo - li - a(href='#') bar - li.last - a(href='#') baz - -### Block Expansion - - Block expansion allows you to create terse single-line nested tags, - the following example is equivalent to the nesting example above. - - ul - li.first: a(href='#') foo - li: a(href='#') bar - li.last: a(href='#') baz - -### Case - - The case statement takes the following form: - - html - body - friends = 10 - case friends - when 0 - p you have no friends - when 1 - p you have a friend - default - p you have #{friends} friends - - Block expansion may also be used: - - friends = 5 - - html - body - case friends - when 0: p you have no friends - when 1: p you have a friend - default: p you have #{friends} friends - -### Attributes - -Jade currently supports '(' and ')' as attribute delimiters. - - a(href='/login', title='View login page') Login - -When a value is `undefined` or `null` the attribute is _not_ added, -so this is fine, it will not compile 'something="null"'. - - div(something=null) - -Boolean attributes are also supported: - - input(type="checkbox", checked) - -Boolean attributes with code will only output the attribute when `true`: - - input(type="checkbox", checked=someValue) - -Multiple lines work too: - - input(type='checkbox', - name='agreement', - checked) - -Multiple lines without the comma work fine: - - input(type='checkbox' - name='agreement' - checked) - -Funky whitespace? fine: - - - input( - type='checkbox' - name='agreement' - checked) - -Colons work: - - rss(xmlns:atom="atom") - -Suppose we have the `user` local `{ id: 12, name: 'tobi' }` -and we wish to create an anchor tag with `href` pointing to "/user/12" -we could use regular javascript concatenation: - - a(href='/user/' + user.id)= user.name - -or we could use jade's interpolation, which I added because everyone -using Ruby or CoffeeScript seems to think this is legal js..: - - a(href='/user/#{user.id}')= user.name - -The `class` attribute is special-cased when an array is given, -allowing you to pass an array such as `bodyClasses = ['user', 'authenticated']` directly: - - body(class=bodyClasses) - -### HTML - - Inline html is fine, we can use the pipe syntax to - write arbitrary text, in this case some html: - -``` -html - body - |foo bar baz
-``` - - Or we can use the trailing `.` to indicate to Jade that we - only want text in this block, allowing us to omit the pipes: - -``` -html - body. -foo bar baz
-``` - - Both of these examples yield the same result: - -``` -foo bar baz
- -``` - - The same rule applies for anywhere you can have text - in jade, raw html is fine: - -``` -html - body - h1 User #{name} -``` - -### Doctypes - -To add a doctype simply use `!!!`, or `doctype` followed by an optional value: - - !!! - -Will output the _transitional_ doctype, however: - - !!! 5 - -or - - !!! html - -or - - doctype html - -doctypes are case-insensitive, so the following are equivalent: - - doctype Basic - doctype basic - -it's also possible to simply pass a doctype literal: - - doctype html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN - -yielding: - - ', - 'default': '', - 'transitional': '', - 'strict': '', - 'frameset': '', - '1.1': '', - 'basic': '', - 'mobile': '' - }; -``` - -To alter the default simply change: - -```javascript - jade.doctypes.default = 'whatever you want'; -``` - -## Filters - -Filters are prefixed with `:`, for example `:markdown` and -pass the following block of text to an arbitrary function for processing. View the _features_ -at the top of this document for available filters. - - body - :markdown - Woah! jade _and_ markdown, very **cool** - we can even link to [stuff](http://google.com) - -Renders: - -Woah! jade and markdown, very cool we can even link to stuff
- -## Code - -Jade currently supports three classifications of executable code. The first -is prefixed by `-`, and is not buffered: - - - var foo = 'bar'; - -This can be used for conditionals, or iteration: - - - for (var key in obj) - p= obj[key] - -Due to Jade's buffering techniques the following is valid as well: - - - if (foo) - ul - li yay - li foo - li worked - - else - p oh no! didnt work - -Hell, even verbose iteration: - - - if (items.length) - ul - - items.forEach(function(item){ - li= item - - }) - -Anything you want! - -Next up we have _escaped_ buffered code, which is used to -buffer a return value, which is prefixed by `=`: - - - var foo = 'bar' - = foo - h1= foo - -Which outputs `barWelcome to my super lame site.
- - - -``` - - As mentioned `include` can be used to include other content - such as html or css. By providing an extension Jade will not - assume that the file is Jade source and will include it as - a literal: - -``` -html - body - include content.html -``` - - Include directives may also accept a block, in which case the - the given block will be appended to the _last_ block defined - in the file. For example if `head.jade` contains: - -``` -head - script(src='/jquery.js') -``` - - We may append values by providing a block to `include head` - as shown below, adding the two scripts. - -``` -html - include head - script(src='/foo.js') - script(src='/bar.js') - body - h1 test -``` - - You may also `yield` within an included template, allowing you to explicitly mark where the block given to `include` will be placed. Suppose for example you wish to prepend scripts rather than append, you might do the following: - -``` -head - yield - script(src='/jquery.js') - script(src='/jquery.ui.js') -``` - - Since included Jade is parsed and literally merges the AST, lexically scoped variables function as if the included Jade was written right in the same file. This means `include` may be used as sort of partial, for example support we have `user.jade` which utilizes a `user` variable. - -``` -h1= user.name -p= user.occupation -``` - -We could then simply `include user` while iterating users, and since the `user` variable is already defined within the loop the included template will have access to it. - -``` -users = [{ name: 'Tobi', occupation: 'Ferret' }] - -each user in users - .user - include user -``` - -yielding: - -```html -Ferret
-'); - buf.push('Just an example'); - buf.push('
'); - } - return buf.join(""); - } catch (err) { - rethrow(err, __.input, __.filename, __.lineno); - } -} -``` - -When the `compileDebug` option _is_ explicitly `false`, this instrumentation -is stripped, which is very helpful for light-weight client-side templates. Combining Jade's options with the `./runtime.js` file in this repo allows you -to toString() compiled templates and avoid running the entire Jade library on -the client, increasing performance, and decreasing the amount of JavaScript -required. - -```js -function anonymous(locals) { - var attrs = jade.attrs, escape = jade.escape; - var buf = []; - with (locals || {}) { - var interp; - var title = 'yay' - buf.push(''); - buf.push('Just an example'); - buf.push('
'); - } - return buf.join(""); -} -``` - -## Example Makefile - - Below is an example Makefile used to compile _pages/*.jade_ - into _pages/*.html_ files by simply executing `make`. - -```make -JADE = $(shell find pages/*.jade) -HTML = $(JADE:.jade=.html) - -all: $(HTML) - -%.html: %.jade - jade < $< --path $< > $@ - -clean: - rm -f $(HTML) - -.PHONY: clean -``` - -this can be combined with the `watch(1)` command to produce -a watcher-like behaviour: - - $ watch make - -## jade(1) - -``` - -Usage: jade [options] [dir|file ...] - -Options: - - -h, --help output usage information - -v, --version output the version number - -o, --objProblem' + (isFinite(c.line) ? ' at line ' + - c.line + ' character ' + c.character : '') + - ': ' + c.reason.entityify() + - '
' + - (e && (e.length > 80 ? e.slice(0, 77) + '...' : - e).entityify()) + '
'); - } - } - } - - if (data.implieds) { - s = []; - for (i = 0; i < data.implieds.length; i += 1) { - s[i] = '' + data.implieds[i].name + '
' +
- data.implieds[i].line + '';
- }
- o.push('Implied global: ' + s.join(', ') + '
'); - } - - if (data.unused) { - s = []; - for (i = 0; i < data.unused.length; i += 1) { - s[i] = '' + data.unused[i].name + '
' +
- data.unused[i].line + ' ' +
- data.unused[i]['function'] + '
';
- }
- o.push('Unused variable: ' + s.join(', ') + '
'); - } - if (data.json) { - o.push('JSON: bad.
'); - } - o.push('JSON: good.
'); - } else if (data.globals) { - o.push('/*members '; - l = 10; - for (i = 0; i < a.length; i += 1) { - k = a[i]; - n = k.name(); - if (l + n.length > 72) { - o.push(m + ''); - } - o.push('
'); - m = ' '; - l = 1; - } - l += n.length + 2; - if (data.member[k] === 1) { - n = '' + n + ''; - } - if (i < a.length - 1) { - n += ', '; - } - m += n; - } - o.push(m + '
*/
%s
' + str + ''); - el.append(err); - } - - // toggle code - el.find('h2').toggle(function(){ - pre.slideDown('fast'); - }, function(){ - pre.slideUp('fast'); - }); - - // code - // TODO: defer - if (!test.pending) { - var code = utils.escape(clean(test.fn.toString())); - var pre = $('
' + code + '
');
- pre.appendTo(el).hide();
- }
- stack[0].append(el);
- });
-
- runner.on('end', function(){
- process.exit(stats.failures);
- });
-}
-
-function error(msg) {
- $('%s
' + str + ''); - el.append(err); - } - - // toggle code - el.find('h2').toggle(function(){ - pre.slideDown('fast'); - }, function(){ - pre.slideUp('fast'); - }); - - // code - // TODO: defer - if (!test.pending) { - var code = utils.escape(clean(test.fn.toString())); - var pre = $('
' + code + '
');
- pre.appendTo(el).hide();
- }
- stack[0].append(el);
- });
-
- runner.on('end', function(){
- process.exit(stats.failures);
- });
-}
-
-function error(msg) {
- $('- -
- -- Underscore is a - utility-belt library for JavaScript that provides a lot of the - functional programming support that you would expect in - Prototype.js - (or Ruby), - but without extending any of the built-in JavaScript objects. It's the - tie to go along with jQuery's tux, - and Backbone.js's suspenders. -
- -- Underscore provides 60-odd functions that support both the usual - functional suspects: map, select, invoke — - as well as more specialized helpers: function binding, javascript - templating, deep equality testing, and so on. It delegates to built-in - functions, if present, so modern browsers will use the - native implementations of forEach, map, reduce, - filter, every, some and indexOf. -
- -- A complete Test & Benchmark Suite - is included for your perusal. -
- -- You may also read through the annotated source code. -
- -- The project is - hosted on GitHub. - You can report bugs and discuss features on the - issues page, - on Freenode in the #documentcloud channel, - or send tweets to @documentcloud. -
- -- Underscore is an open-source component of DocumentCloud. -
- -Development Version (1.2.4) | -34kb, Uncompressed with Comments | -
Production Version (1.2.4) | -< 4kb, Minified and Gzipped | -
- each_.each(list, iterator, [context])
- Alias: forEach
-
- Iterates over a list of elements, yielding each in turn to an iterator
- function. The iterator is bound to the context object, if one is
- passed. Each invocation of iterator is called with three arguments:
- (element, index, list). If list is a JavaScript object, iterator's
- arguments will be (value, key, list). Delegates to the native
- forEach function if it exists.
-
-_.each([1, 2, 3], function(num){ alert(num); }); -=> alerts each number in turn... -_.each({one : 1, two : 2, three : 3}, function(num, key){ alert(num); }); -=> alerts each number in turn...- -
- map_.map(list, iterator, [context])
-
- Produces a new array of values by mapping each value in list
- through a transformation function (iterator). If the native map method
- exists, it will be used instead. If list is a JavaScript object,
- iterator's arguments will be (value, key, list).
-
-_.map([1, 2, 3], function(num){ return num * 3; }); -=> [3, 6, 9] -_.map({one : 1, two : 2, three : 3}, function(num, key){ return num * 3; }); -=> [3, 6, 9]- -
- reduce_.reduce(list, iterator, memo, [context])
- Aliases: inject, foldl
-
- Also known as inject and foldl, reduce boils down a
- list of values into a single value. Memo is the initial state
- of the reduction, and each successive step of it should be returned by
- iterator.
-
-var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0); -=> 6 -- -
- reduceRight_.reduceRight(list, iterator, memo, [context])
- Alias: foldr
-
- The right-associative version of reduce. Delegates to the
- JavaScript 1.8 version of reduceRight, if it exists. Foldr
- is not as useful in JavaScript as it would be in a language with lazy
- evaluation.
-
-var list = [[0, 1], [2, 3], [4, 5]]; -var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); -=> [4, 5, 2, 3, 0, 1] -- -
- find_.find(list, iterator, [context])
- Alias: detect
-
- Looks through each value in the list, returning the first one that
- passes a truth test (iterator). The function returns as
- soon as it finds an acceptable element, and doesn't traverse the
- entire list.
-
-var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); -=> 2 -- -
- filter_.filter(list, iterator, [context])
- Alias: select
-
- Looks through each value in the list, returning an array of all
- the values that pass a truth test (iterator). Delegates to the
- native filter method, if it exists.
-
-var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); -=> [2, 4, 6] -- -
- reject_.reject(list, iterator, [context])
-
- Returns the values in list without the elements that the truth
- test (iterator) passes. The opposite of filter.
-
-var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); -=> [1, 3, 5] -- -
- all_.all(list, iterator, [context])
- Alias: every
-
- Returns true if all of the values in the list pass the iterator
- truth test. Delegates to the native method every, if present.
-
-_.all([true, 1, null, 'yes'], _.identity); -=> false -- -
- any_.any(list, [iterator], [context])
- Alias: some
-
- Returns true if any of the values in the list pass the
- iterator truth test. Short-circuits and stops traversing the list
- if a true element is found. Delegates to the native method some,
- if present.
-
-_.any([null, 0, 'yes', false]); -=> true -- -
- include_.include(list, value)
- Alias: contains
-
- Returns true if the value is present in the list, using
- === to test equality. Uses indexOf internally, if list
- is an Array.
-
-_.include([1, 2, 3], 3); -=> true -- -
- invoke_.invoke(list, methodName, [*arguments])
-
- Calls the method named by methodName on each value in the list.
- Any extra arguments passed to invoke will be forwarded on to the
- method invocation.
-
-_.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); -=> [[1, 5, 7], [1, 2, 3]] -- -
- pluck_.pluck(list, propertyName)
-
- A convenient version of what is perhaps the most common use-case for
- map: extracting a list of property values.
-
-var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}]; -_.pluck(stooges, 'name'); -=> ["moe", "larry", "curly"] -- -
- max_.max(list, [iterator], [context])
-
- Returns the maximum value in list. If iterator is passed,
- it will be used on each value to generate the criterion by which the
- value is ranked.
-
-var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}]; -_.max(stooges, function(stooge){ return stooge.age; }); -=> {name : 'curly', age : 60}; -- -
- min_.min(list, [iterator], [context])
-
- Returns the minimum value in list. If iterator is passed,
- it will be used on each value to generate the criterion by which the
- value is ranked.
-
-var numbers = [10, 5, 100, 2, 1000]; -_.min(numbers); -=> 2 -- -
- sortBy_.sortBy(list, iterator, [context])
-
- Returns a sorted copy of list, ranked by the results of running
- each value through iterator.
-
-_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); }); -=> [5, 4, 6, 3, 1, 2] -- -
- groupBy_.groupBy(list, iterator)
-
- Splits a collection into sets, grouped by the result of running each
- value through iterator. If iterator is a string instead of
- a function, groups by the property named by iterator on each of
- the values.
-
-_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); }); -=> {1: [1.3], 2: [2.1, 2.4]} - -_.groupBy(['one', 'two', 'three'], 'length'); -=> {3: ["one", "two"], 5: ["three"]} -- -
- sortedIndex_.sortedIndex(list, value, [iterator])
-
- Uses a binary search to determine the index at which the value
- should be inserted into the list in order to maintain the list's
- sorted order. If an iterator is passed, it will be used to compute
- the sort ranking of each value.
-
-_.sortedIndex([10, 20, 30, 40, 50], 35); -=> 3 -- -
- shuffle_.shuffle(list)
-
- Returns a shuffled copy of the list, using a version of the
- Fisher-Yates shuffle.
-
-_.shuffle([1, 2, 3, 4, 5, 6]); -=> [4, 1, 6, 3, 5, 2] -- -
- toArray_.toArray(list)
-
- Converts the list (anything that can be iterated over), into a
- real Array. Useful for transmuting the arguments object.
-
-(function(){ return _.toArray(arguments).slice(0); })(1, 2, 3); -=> [1, 2, 3] -- -
- size_.size(list)
-
- Return the number of values in the list.
-
-_.size({one : 1, two : 2, three : 3}); -=> 3 -- -
- Note: All array functions will also work on the arguments object. -
- -
- first_.first(array, [n])
- Alias: head
-
- Returns the first element of an array. Passing n will
- return the first n elements of the array.
-
-_.first([5, 4, 3, 2, 1]); -=> 5 -- -
- initial_.initial(array, [n])
-
- Returns everything but the last entry of the array. Especially useful on
- the arguments object. Pass n to exclude the last n elements
- from the result.
-
-_.initial([5, 4, 3, 2, 1]); -=> [5, 4, 3, 2] -- -
- last_.last(array, [n])
-
- Returns the last element of an array. Passing n will return
- the last n elements of the array.
-
-_.last([5, 4, 3, 2, 1]); -=> 1 -- -
- rest_.rest(array, [index])
- Alias: tail
-
- Returns the rest of the elements in an array. Pass an index
- to return the values of the array from that index onward.
-
-_.rest([5, 4, 3, 2, 1]); -=> [4, 3, 2, 1] -- -
- compact_.compact(array)
-
- Returns a copy of the array with all falsy values removed.
- In JavaScript, false, null, 0, "",
- undefined and NaN are all falsy.
-
-_.compact([0, 1, false, 2, '', 3]); -=> [1, 2, 3] -- -
- flatten_.flatten(array)
-
- Flattens a nested array (the nesting can be to any depth).
-
-_.flatten([1, [2], [3, [[[4]]]]]); -=> [1, 2, 3, 4]; -- -
- without_.without(array, [*values])
-
- Returns a copy of the array with all instances of the values
- removed. === is used for the equality test.
-
-_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); -=> [2, 3, 4] -- -
- union_.union(*arrays)
-
- Computes the union of the passed-in arrays: the list of unique items,
- in order, that are present in one or more of the arrays.
-
-_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); -=> [1, 2, 3, 101, 10] -- -
- intersection_.intersection(*arrays)
-
- Computes the list of values that are the intersection of all the arrays.
- Each value in the result is present in each of the arrays.
-
-_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); -=> [1, 2] -- -
- difference_.difference(array, *others)
-
- Similar to without, but returns the values from array that
- are not present in the other arrays.
-
-_.difference([1, 2, 3, 4, 5], [5, 2, 10]); -=> [1, 3, 4] -- -
- uniq_.uniq(array, [isSorted], [iterator])
- Alias: unique
-
- Produces a duplicate-free version of the array, using === to test
- object equality. If you know in advance that the array is sorted,
- passing true for isSorted will run a much faster algorithm.
- If you want to compute unique items based on a transformation, pass an
- iterator function.
-
-_.uniq([1, 2, 1, 3, 1, 4]); -=> [1, 2, 3, 4] -- -
- zip_.zip(*arrays)
-
- Merges together the values of each of the arrays with the
- values at the corresponding position. Useful when you have separate
- data sources that are coordinated through matching array indexes.
- If you're working with a matrix of nested arrays, zip.apply
- can transpose the matrix in a similar fashion.
-
-_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); -=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]] -- -
- indexOf_.indexOf(array, value, [isSorted])
-
- Returns the index at which value can be found in the array,
- or -1 if value is not present in the array. Uses the native
- indexOf function unless it's missing. If you're working with a
- large array, and you know that the array is already sorted, pass true
- for isSorted to use a faster binary search.
-
-_.indexOf([1, 2, 3], 2); -=> 1 -- -
- lastIndexOf_.lastIndexOf(array, value)
-
- Returns the index of the last occurrence of value in the array,
- or -1 if value is not present. Uses the native lastIndexOf
- function if possible.
-
-_.lastIndexOf([1, 2, 3, 1, 2, 3], 2); -=> 4 -- -
- range_.range([start], stop, [step])
-
- A function to create flexibly-numbered lists of integers, handy for
- each and map loops. start, if omitted, defaults
- to 0; step defaults to 1. Returns a list of integers
- from start to stop, incremented (or decremented) by step,
- exclusive.
-
-_.range(10); -=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] -_.range(1, 11); -=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] -_.range(0, 30, 5); -=> [0, 5, 10, 15, 20, 25] -_.range(0, -10, -1); -=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] -_.range(0); -=> [] -- -
- bind_.bind(function, object, [*arguments])
-
- Bind a function to an object, meaning that whenever
- the function is called, the value of this will be the object.
- Optionally, bind arguments to the function to pre-fill them,
- also known as partial application.
-
-var func = function(greeting){ return greeting + ': ' + this.name }; -func = _.bind(func, {name : 'moe'}, 'hi'); -func(); -=> 'hi: moe' -- -
- bindAll_.bindAll(object, [*methodNames])
-
- Binds a number of methods on the object, specified by
- methodNames, to be run in the context of that object whenever they
- are invoked. Very handy for binding functions that are going to be used
- as event handlers, which would otherwise be invoked with a fairly useless
- this. If no methodNames are provided, all of the object's
- function properties will be bound to it.
-
-var buttonView = { - label : 'underscore', - onClick : function(){ alert('clicked: ' + this.label); }, - onHover : function(){ console.log('hovering: ' + this.label); } -}; -_.bindAll(buttonView); -jQuery('#underscore_button').bind('click', buttonView.onClick); -=> When the button is clicked, this.label will have the correct value... -- -
- memoize_.memoize(function, [hashFunction])
-
- Memoizes a given function by caching the computed result. Useful
- for speeding up slow-running computations. If passed an optional
- hashFunction, it will be used to compute the hash key for storing
- the result, based on the arguments to the original function. The default
- hashFunction just uses the first argument to the memoized function
- as the key.
-
-var fibonacci = _.memoize(function(n) { - return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); -}); -- -
- delay_.delay(function, wait, [*arguments])
-
- Much like setTimeout, invokes function after wait
- milliseconds. If you pass the optional arguments, they will be
- forwarded on to the function when it is invoked.
-
-var log = _.bind(console.log, console); -_.delay(log, 1000, 'logged later'); -=> 'logged later' // Appears after one second. -- -
- defer_.defer(function)
-
- Defers invoking the function until the current call stack has cleared,
- similar to using setTimeout with a delay of 0. Useful for performing
- expensive computations or HTML rendering in chunks without blocking the UI thread
- from updating.
-
-_.defer(function(){ alert('deferred'); }); -// Returns from the function before the alert runs. -- -
- throttle_.throttle(function, wait)
-
- Creates and returns a new, throttled version of the passed function,
- that, when invoked repeatedly, will only actually call the original function
- at most once per every wait
- milliseconds. Useful for rate-limiting events that occur faster than you
- can keep up with.
-
-var throttled = _.throttle(updatePosition, 100); -$(window).scroll(throttled); -- -
- debounce_.debounce(function, wait)
-
- Creates and returns a new debounced version of the passed function that
- will postpone its execution until after
- wait milliseconds have elapsed since the last time it
- was invoked. Useful for implementing behavior that should only happen
- after the input has stopped arriving. For example: rendering a
- preview of a Markdown comment, recalculating a layout after the window
- has stopped being resized, and so on.
-
-var lazyLayout = _.debounce(calculateLayout, 300); -$(window).resize(lazyLayout); -- -
- once_.once(function)
-
- Creates a version of the function that can only be called one time.
- Repeated calls to the modified function will have no effect, returning
- the value from the original call. Useful for initialization functions,
- instead of having to set a boolean flag and then check it later.
-
-var initialize = _.once(createApplication); -initialize(); -initialize(); -// Application is only created once. -- -
- after_.after(count, function)
-
- Creates a version of the function that will only be run after first
- being called count times. Useful for grouping asynchronous responses,
- where you want to be sure that all the async calls have finished, before
- proceeding.
-
-var renderNotes = _.after(notes.length, render); -_.each(notes, function(note) { - note.asyncSave({success: renderNotes}); -}); -// renderNotes is run once, after all notes have saved. -- -
- wrap_.wrap(function, wrapper)
-
- Wraps the first function inside of the wrapper function,
- passing it as the first argument. This allows the wrapper to
- execute code before and after the function runs, adjust the arguments,
- and execute it conditionally.
-
-var hello = function(name) { return "hello: " + name; }; -hello = _.wrap(hello, function(func) { - return "before, " + func("moe") + ", after"; -}); -hello(); -=> 'before, hello: moe, after' -- -
- compose_.compose(*functions)
-
- Returns the composition of a list of functions, where each function
- consumes the return value of the function that follows. In math terms,
- composing the functions f(), g(), and h() produces
- f(g(h())).
-
-var greet = function(name){ return "hi: " + name; }; -var exclaim = function(statement){ return statement + "!"; }; -var welcome = _.compose(exclaim, greet); -welcome('moe'); -=> 'hi: moe!' -- -
- keys_.keys(object)
-
- Retrieve all the names of the object's properties.
-
-_.keys({one : 1, two : 2, three : 3}); -=> ["one", "two", "three"] -- -
- values_.values(object)
-
- Return all of the values of the object's properties.
-
-_.values({one : 1, two : 2, three : 3}); -=> [1, 2, 3] -- -
- functions_.functions(object)
- Alias: methods
-
- Returns a sorted list of the names of every method in an object —
- that is to say, the name of every function property of the object.
-
-_.functions(_); -=> ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ... -- -
- extend_.extend(destination, *sources)
-
- Copy all of the properties in the source objects over to the
- destination object. It's in-order, so the last source will override
- properties of the same name in previous arguments.
-
-_.extend({name : 'moe'}, {age : 50}); -=> {name : 'moe', age : 50} -- -
- defaults_.defaults(object, *defaults)
-
- Fill in missing properties in object with default values from the
- defaults objects. As soon as the property is filled, further defaults
- will have no effect.
-
-var iceCream = {flavor : "chocolate"}; -_.defaults(iceCream, {flavor : "vanilla", sprinkles : "lots"}); -=> {flavor : "chocolate", sprinkles : "lots"} -- -
- clone_.clone(object)
-
- Create a shallow-copied clone of the object. Any nested objects
- or arrays will be copied by reference, not duplicated.
-
-_.clone({name : 'moe'}); -=> {name : 'moe'}; -- -
- tap_.tap(object, interceptor)
-
- Invokes interceptor with the object, and then returns object.
- The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.
-
-_.chain([1,2,3,200]) - .filter(function(num) { return num % 2 == 0; }) - .tap(console.log) - .map(function(num) { return num * num }) - .value(); -=> [2, 200] -=> [4, 40000] -- -
- isEqual_.isEqual(object, other)
-
- Performs an optimized deep comparison between the two objects, to determine
- if they should be considered equal.
-
-var moe = {name : 'moe', luckyNumbers : [13, 27, 34]}; -var clone = {name : 'moe', luckyNumbers : [13, 27, 34]}; -moe == clone; -=> false -_.isEqual(moe, clone); -=> true -- -
- isEmpty_.isEmpty(object)
-
- Returns true if object contains no values.
-
-_.isEmpty([1, 2, 3]); -=> false -_.isEmpty({}); -=> true -- -
- isElement_.isElement(object)
-
- Returns true if object is a DOM element.
-
-_.isElement(jQuery('body')[0]); -=> true -- -
- isArray_.isArray(object)
-
- Returns true if object is an Array.
-
-(function(){ return _.isArray(arguments); })(); -=> false -_.isArray([1,2,3]); -=> true -- -
- isArguments_.isArguments(object)
-
- Returns true if object is an Arguments object.
-
-(function(){ return _.isArguments(arguments); })(1, 2, 3); -=> true -_.isArguments([1,2,3]); -=> false -- -
- isFunction_.isFunction(object)
-
- Returns true if object is a Function.
-
-_.isFunction(alert); -=> true -- -
- isString_.isString(object)
-
- Returns true if object is a String.
-
-_.isString("moe"); -=> true -- -
- isNumber_.isNumber(object)
-
- Returns true if object is a Number (including NaN).
-
-_.isNumber(8.4 * 5); -=> true -- -
- isBoolean_.isBoolean(object)
-
- Returns true if object is either true or false.
-
-_.isBoolean(null); -=> false -- -
- isDate_.isDate(object)
-
- Returns true if object is a Date.
-
-_.isDate(new Date()); -=> true -- -
- isRegExp_.isRegExp(object)
-
- Returns true if object is a RegExp.
-
-_.isRegExp(/moe/); -=> true -- -
- isNaN_.isNaN(object)
-
- Returns true if object is NaN.
Note: this is not
- the same as the native isNaN function, which will also return
- true if the variable is undefined.
-
-_.isNaN(NaN); -=> true -isNaN(undefined); -=> true -_.isNaN(undefined); -=> false -- -
- isNull_.isNull(object)
-
- Returns true if the value of object is null.
-
-_.isNull(null); -=> true -_.isNull(undefined); -=> false -- -
- isUndefined_.isUndefined(variable)
-
- Returns true if variable is undefined.
-
-_.isUndefined(window.missingVariable); -=> true -- -
- noConflict_.noConflict()
-
- Give control of the "_" variable back to its previous owner. Returns
- a reference to the Underscore object.
-
-var underscore = _.noConflict();- -
- identity_.identity(value)
-
- Returns the same value that is used as the argument. In math:
- f(x) = x
- This function looks useless, but is used throughout Underscore as
- a default iterator.
-
-var moe = {name : 'moe'}; -moe === _.identity(moe); -=> true- -
- times_.times(n, iterator)
-
- Invokes the given iterator function n times.
-
-_(3).times(function(){ genie.grantWish(); });- -
- mixin_.mixin(object)
-
- Allows you to extend Underscore with your own utility functions. Pass
- a hash of {name: function} definitions to have your functions
- added to the Underscore object, as well as the OOP wrapper.
-
-_.mixin({ - capitalize : function(string) { - return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase(); - } -}); -_("fabio").capitalize(); -=> "Fabio" -- -
- uniqueId_.uniqueId([prefix])
-
- Generate a globally-unique id for client-side models or DOM elements
- that need one. If prefix is passed, the id will be appended to it.
-
-_.uniqueId('contact_'); -=> 'contact_104'- -
- escape_.escape(string)
-
- Escapes a string for insertion into HTML, replacing
- &, <, >, ", ', and / characters.
-
-_.escape('Curly, Larry & Moe'); -=> "Curly, Larry & Moe"- -
- template_.template(templateString, [context])
-
- Compiles JavaScript templates into functions that can be evaluated
- for rendering. Useful for rendering complicated bits of HTML from JSON
- data sources. Template functions can both interpolate variables, using
- <%= … %>, as well as execute arbitrary JavaScript code, with
- <% … %>. If you wish to interpolate a value, and have
- it be HTML-escaped, use <%- … %> When you evaluate a template function, pass in a
- context object that has properties corresponding to the template's free
- variables. If you're writing a one-off, you can pass the context
- object as the second parameter to template in order to render
- immediately instead of returning a template function.
-
-var compiled = _.template("hello: <%= name %>"); -compiled({name : 'moe'}); -=> "hello: moe" - -var list = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>"; -_.template(list, {people : ['moe', 'curly', 'larry']}); -=> "<li>moe</li><li>curly</li><li>larry</li>" - -var template = _.template("<b><%- value %></b>"); -template({value : '<script>'}); -=> "<b><script></b>"- -
- You can also use print from within JavaScript code. This is - sometimes more convenient than using <%= ... %>. -
- --var compiled = _.template("<% print('Hello ' + epithet); %>"); -compiled({epithet: "stooge"}); -=> "Hello stooge."- -
- If ERB-style delimiters aren't your cup of tea, you can change Underscore's - template settings to use different symbols to set off interpolated code. - Define an interpolate regex to match expressions that should be - interpolated verbatim, an escape regex to match expressions that should - be inserted after being HTML escaped, and an evaluate regex to match - expressions that should be evaluated without insertion into the resulting - string. You may define or omit any combination of the three. - For example, to perform - Mustache.js - style templating: -
- --_.templateSettings = { - interpolate : /\{\{(.+?)\}\}/g -}; - -var template = _.template("Hello {{ name }}!"); -template({name : "Mustache"}); -=> "Hello Mustache!"- - -
- You can use Underscore in either an object-oriented or a functional style, - depending on your preference. The following two lines of code are - identical ways to double a list of numbers. -
- --_.map([1, 2, 3], function(n){ return n * 2; }); -_([1, 2, 3]).map(function(n){ return n * 2; });- -
- Using the object-oriented style allows you to chain together methods. Calling - chain on a wrapped object will cause all future method calls to - return wrapped objects as well. When you've finished the computation, - use value to retrieve the final value. Here's an example of chaining - together a map/flatten/reduce, in order to get the word count of - every word in a song. -
- --var lyrics = [ - {line : 1, words : "I'm a lumberjack and I'm okay"}, - {line : 2, words : "I sleep all night and I work all day"}, - {line : 3, words : "He's a lumberjack and he's okay"}, - {line : 4, words : "He sleeps all night and he works all day"} -]; - -_.chain(lyrics) - .map(function(line) { return line.words.split(' '); }) - .flatten() - .reduce(function(counts, word) { - counts[word] = (counts[word] || 0) + 1; - return counts; -}, {}).value(); - -=> {lumberjack : 2, all : 4, night : 2 ... }- -
- In addition, the - Array prototype's methods - are proxied through the chained Underscore object, so you can slip a - reverse or a push into your chain, and continue to - modify the array. -
- -
- chain_.chain(obj)
-
- Returns a wrapped object. Calling methods on this object will continue
- to return wrapped objects until value is used.
-
-var stooges = [{name : 'curly', age : 25}, {name : 'moe', age : 21}, {name : 'larry', age : 23}]; -var youngest = _.chain(stooges) - .sortBy(function(stooge){ return stooge.age; }) - .map(function(stooge){ return stooge.name + ' is ' + stooge.age; }) - .first() - .value(); -=> "moe is 21" -- -
- value_(obj).value()
-
- Extracts the value of a wrapped object.
-
-_([1, 2, 3]).value(); -=> [1, 2, 3] -- -
- Underscore.lua, - a Lua port of the functions that are applicable in both languages. - Includes OOP-wrapping and chaining. - The source is - available on GitHub. -
- -- Underscore.php, - a PHP port of the functions that are applicable in both languages. - Includes OOP-wrapping and chaining. - The source is - available on GitHub. -
- -- Underscore-perl, - a Perl port of many of the Underscore.js functions, - aimed at on Perl hashes and arrays, also - available on GitHub. -
- -- Underscore.string, - an Underscore extension that adds functions for string-manipulation: - trim, startsWith, contains, capitalize, - reverse, sprintf, and more. -
- -- Ruby's Enumerable module. -
- -- Prototype.js, which provides - JavaScript with collection functions in the manner closest to Ruby's Enumerable. -
- -- Oliver Steele's - Functional JavaScript, - which includes comprehensive higher-order function support as well as string lambdas. -
- -- Michael Aufreiter's Data.js, - a data manipulation + persistence library for JavaScript. -
- -- Python's itertools. -
- -
- 1.2.4 — Jan. 4, 2012
-
- 1.2.3 — Dec. 7, 2011
-
- 1.2.2 — Nov. 14, 2011
-
- 1.2.1 — Oct. 24, 2011
-
- 1.2.0 — Oct. 5, 2011
-
- 1.1.7 — July 13, 2011
- Added _.groupBy, which aggregates a collection into groups of like items.
- Added _.union and _.difference, to complement the
- (re-named) _.intersection.
- Various improvements for support of sparse arrays.
- _.toArray now returns a clone, if directly passed an array.
- _.functions now also returns the names of functions that are present
- in the prototype chain.
-
- 1.1.6 — April 18, 2011
- Added _.after, which will return a function that only runs after
- first being called a specified number of times.
- _.invoke can now take a direct function reference.
- _.every now requires an iterator function to be passed, which
- mirrors the ECMA5 API.
- _.extend no longer copies keys when the value is undefined.
- _.bind now errors when trying to bind an undefined value.
-
- 1.1.5 — Mar 20, 2011
- Added an _.defaults function, for use merging together JS objects
- representing default options.
- Added an _.once function, for manufacturing functions that should
- only ever execute a single time.
- _.bind now delegates to the native ECMAScript 5 version,
- where available.
- _.keys now throws an error when used on non-Object values, as in
- ECMAScript 5.
- Fixed a bug with _.keys when used over sparse arrays.
-
- 1.1.4 — Jan 9, 2011
- Improved compliance with ES5's Array methods when passing null
- as a value. _.wrap now correctly sets this for the
- wrapped function. _.indexOf now takes an optional flag for
- finding the insertion index in an array that is guaranteed to already
- be sorted. Avoiding the use of .callee, to allow _.isArray
- to work properly in ES5's strict mode.
-
- 1.1.3 — Dec 1, 2010
- In CommonJS, Underscore may now be required with just:
- var _ = require("underscore").
- Added _.throttle and _.debounce functions.
- Removed _.breakLoop, in favor of an ECMA5-style un-break-able
- each implementation — this removes the try/catch, and you'll now have
- better stack traces for exceptions that are thrown within an Underscore iterator.
- Improved the isType family of functions for better interoperability
- with Internet Explorer host objects.
- _.template now correctly escapes backslashes in templates.
- Improved _.reduce compatibility with the ECMA5 version:
- if you don't pass an initial value, the first item in the collection is used.
- _.each no longer returns the iterated collection, for improved
- consistency with ES5's forEach.
-
- 1.1.2
- Fixed _.contains, which was mistakenly pointing at
- _.intersect instead of _.include, like it should
- have been. Added _.unique as an alias for _.uniq.
-
- 1.1.1
- Improved the speed of _.template, and its handling of multiline
- interpolations. Ryan Tenney contributed optimizations to many Underscore
- functions. An annotated version of the source code is now available.
-
- 1.1.0
- The method signature of _.reduce has been changed to match
- the ECMAScript 5 signature, instead of the Ruby/Prototype.js version.
- This is a backwards-incompatible change. _.template may now be
- called with no arguments, and preserves whitespace. _.contains
- is a new alias for _.include.
-
- 1.0.4
- Andri Möll contributed the _.memoize
- function, which can be used to speed up expensive repeated computations
- by caching the results.
-
- 1.0.3
- Patch that makes _.isEqual return false if any property
- of the compared object has a NaN value. Technically the correct
- thing to do, but of questionable semantics. Watch out for NaN comparisons.
-
- 1.0.2
- Fixes _.isArguments in recent versions of Opera, which have
- arguments objects as real Arrays.
-
- 1.0.1
- Bugfix for _.isEqual, when comparing two objects with the same
- number of undefined keys, but with different names.
-
- 1.0.0
- Things have been stable for many months now, so Underscore is now
- considered to be out of beta, at 1.0. Improvements since 0.6
- include _.isBoolean, and the ability to have _.extend
- take multiple source objects.
-
- 0.6.0
- Major release. Incorporates a number of
- Mile Frawley's refactors for
- safer duck-typing on collection functions, and cleaner internals. A new
- _.mixin method that allows you to extend Underscore with utility
- functions of your own. Added _.times, which works the same as in
- Ruby or Prototype.js. Native support for ECMAScript 5's Array.isArray,
- and Object.keys.
-
- 0.5.8
- Fixed Underscore's collection functions to work on
- NodeLists and
- HTMLCollections
- once more, thanks to
- Justin Tulloss.
-
- 0.5.7
- A safer implementation of _.isArguments, and a
- faster _.isNumber,
thanks to
- Jed Schmidt.
-
- 0.5.6
- Customizable delimiters for _.template, contributed by
- Noah Sloan.
-
- 0.5.5
- Fix for a bug in MobileSafari's OOP-wrapper, with the arguments object.
-
- 0.5.4
- Fix for multiple single quotes within a template string for
- _.template. See:
- Rick Strahl's blog post.
-
- 0.5.2
- New implementations of isArray, isDate, isFunction,
- isNumber, isRegExp, and isString, thanks to
- a suggestion from
- Robert Kieffer.
- Instead of doing Object#toString
- comparisons, they now check for expected properties, which is less safe,
- but more than an order of magnitude faster. Most other Underscore
- functions saw minor speed improvements as a result.
- Evgeniy Dolzhenko
- contributed _.tap,
- similar to Ruby 1.9's,
- which is handy for injecting side effects (like logging) into chained calls.
-
- 0.5.1
- Added an _.isArguments function. Lots of little safety checks
- and optimizations contributed by
- Noah Sloan and
- Andri Möll.
-
- 0.5.0
- [API Changes] _.bindAll now takes the context object as
- its first parameter. If no method names are passed, all of the context
- object's methods are bound to it, enabling chaining and easier binding.
- _.functions now takes a single argument and returns the names
- of its Function properties. Calling _.functions(_) will get you
- the previous behavior.
- Added _.isRegExp so that isEqual can now test for RegExp equality.
- All of the "is" functions have been shrunk down into a single definition.
- Karl Guertin contributed patches.
-
- 0.4.7
- Added isDate, isNaN, and isNull, for completeness.
- Optimizations for isEqual when checking equality between Arrays
- or Dates. _.keys is now 25%–2X faster (depending on your
- browser) which speeds up the functions that rely on it, such as _.each.
-
- 0.4.6
- Added the range function, a port of the
- Python
- function of the same name, for generating flexibly-numbered lists
- of integers. Original patch contributed by
- Kirill Ishanov.
-
- 0.4.5
- Added rest for Arrays and arguments objects, and aliased
- first as head, and rest as tail,
- thanks to Luke Sutton's patches.
- Added tests ensuring that all Underscore Array functions also work on
- arguments objects.
-
- 0.4.4
- Added isString, and isNumber, for consistency. Fixed
- _.isEqual(NaN, NaN) to return true (which is debatable).
-
- 0.4.3
- Started using the native StopIteration object in browsers that support it.
- Fixed Underscore setup for CommonJS environments.
-
- 0.4.2
- Renamed the unwrapping function to value, for clarity.
-
- 0.4.1
- Chained Underscore objects now support the Array prototype methods, so
- that you can perform the full range of operations on a wrapped array
- without having to break your chain. Added a breakLoop method
- to break in the middle of any Underscore iteration. Added an
- isEmpty function that works on arrays and objects.
-
- 0.4.0
- All Underscore functions can now be called in an object-oriented style,
- like so: _([1, 2, 3]).map(...);. Original patch provided by
- Marc-André Cournoyer.
- Wrapped objects can be chained through multiple
- method invocations. A functions method
- was added, providing a sorted list of all the functions in Underscore.
-
- 0.3.3
- Added the JavaScript 1.8 function reduceRight. Aliased it
- as foldr, and aliased reduce as foldl.
-
- 0.3.2
- Now runs on stock Rhino
- interpreters with: load("underscore.js").
- Added identity as a utility function.
-
- 0.3.1
- All iterators are now passed in the original collection as their third
- argument, the same as JavaScript 1.6's forEach. Iterating over
- objects is now called with (value, key, collection), for details
- see _.each.
-
- 0.3.0
- Added Dmitry Baranovskiy's
- comprehensive optimizations, merged in
- Kris Kowal's patches to make Underscore
- CommonJS and
- Narwhal compliant.
-
- 0.2.0
- Added compose and lastIndexOf, renamed inject to
- reduce, added aliases for inject, filter,
- every, some, and forEach.
-
- 0.1.1
- Added noConflict, so that the "Underscore" object can be assigned to
- other variables.
-
- 0.1.0
- Initial release of Underscore.js.
-
- - - -
- - winston.js | |
---|---|
/*
- * winston.js: Top-level include defining Winston.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- *
- */
-
-var winston = exports; | |
Expose version using | require('pkginfo')(module, 'version'); |
Include transports defined by default by winston | winston.transports = require('./winston/transports');
-
-var common = require('./winston/common');
-winston.hash = common.hash;
-winston.clone = common.clone;
-winston.longestElement = common.longestElement;
-winston.exception = require('./winston/exception');
-winston.config = require('./winston/config');
-winston.addColors = winston.config.addColors;
-winston.Logger = require('./winston/logger').Logger;
-winston.Transport = require('./winston/transports/transport').Transport; |
We create and expose a 'defaultLogger' so that the programmer may do the -following without the need to create an instance of winston.Logger directly: - - | var defaultLogger = new winston.Logger({
- transports: [new winston.transports.Console()]
-}); |
Pass through the target methods onto `winston. | var methods = [
- 'log',
- 'add',
- 'remove',
- 'profile',
- 'extend',
- 'cli',
- 'handleExceptions',
- 'unhandleExceptions'
-];
-common.setLevels(winston, null, defaultLogger.levels);
-methods.forEach(function (method) {
- winston[method] = function () {
- return defaultLogger[method].apply(defaultLogger, arguments);
- };
-}); |
function cli ()- -Configures the default winston logger to have the -settings for command-line interfaces: no timestamp, -colors enabled, padded output, and additional levels. | winston.cli = function () {
- winston.padLevels = true;
- common.setLevels(winston, defaultLogger.levels, winston.config.cli.levels);
- defaultLogger.setLevels(winston.config.cli.levels);
- winston.config.addColors(winston.config.cli.colors);
-
- if (defaultLogger.transports.console) {
- defaultLogger.transports.console.colorize = true;
- defaultLogger.transports.console.timestamp = false;
- }
-
- return winston;
-}; |
function setLevels (target)- -@target {Object} Target levels to use- -Sets the | winston.setLevels = function (target) {
- common.setLevels(winston, defaultLogger.levels, target);
- defaultLogger.setLevels(target);
-}; |
Define getters / setters for appropriate properties of the -default logger which need to be exposed by winston. | ['emitErrs', 'padLevels', 'levelLength'].forEach(function (prop) {
- Object.defineProperty(winston, prop, {
- get: function () {
- return defaultLogger[prop];
- },
- set: function (val) {
- defaultLogger[prop] = val;
- }
- });
-}); |
@default {Object} -The default transports and exceptionHandlers for -the default winston logger. | Object.defineProperty(winston, 'default', {
- get: function () {
- return {
- transports: defaultLogger.transports,
- exceptionHandlers: defaultLogger.exceptionHandlers
- };
- }
-});
-
- |
common.js | |
---|---|
/*
- * common.js: Internal helper and utility functions for winston
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- *
- */
-
-var util = require('util'),
- crypto = require('crypto'),
- loggly = require('loggly'),
- config = require('./config'); | |
function setLevels (target, past, current)- -@target {Object} Object on which to set levels.- -@past {Object} Previous levels set on target.- -@current {Object} Current levels to set on target.- -Create functions on the target objects for each level -in current.levels. If past is defined, remove functions -for each of those levels. | exports.setLevels = function (target, past, current, isDefault) {
- if (past) {
- Object.keys(past).forEach(function (level) {
- delete target[level];
- });
- }
-
- target.levels = current || config.npm.levels;
- if (target.padLevels) {
- target.levelLength = exports.longestElement(Object.keys(target.levels));
- }
- |
Define prototype methods for each log level - e.g. target.log('info', msg) <=> target.info(msg) | Object.keys(target.levels).forEach(function (level) {
- target[level] = function (msg) {
- var args = Array.prototype.slice.call(arguments),
- callback = typeof args[args.length - 1] === 'function' ? args.pop() : null,
- meta = args.length === 2 ? args.pop() : null;
-
- return target.log(level, msg, meta, callback);
- };
- });
-
- return target;
-}; |
function longestElement- -@xs {Array} Array to calculate against- -Returns the longest element in the | exports.longestElement = function (xs) {
- return Math.max.apply(
- null,
- xs.map(function (x) { return x.length })
- );
-}; |
function clone (obj)- -@obj {Object} Object to clone.- -Helper method for deep cloning pure JSON objects -i.e. JSON objects that are either literals or objects (no Arrays, etc) | exports.clone = function (obj) {
- var copy = {};
- for (var i in obj) {
- if (Array.isArray(obj[i])) {
- copy[i] = obj[i].slice(0);
- }
- else {
- copy[i] = obj[i] instanceof Object ? exports.clone(obj[i]) : obj[i];
- }
- }
-
- return copy;
-}; |
function log (options)- -@options {Object} All information about the log serialization.- -Generic logging function for returning timestamped strings -with the following options: - -{
- level: 'level to add to serialized message',
- message: 'message to serialize',
- meta: 'additional logging metadata to serialize',
- colorize: false, // Colorizes output (only if | exports.log = function (options) {
- var timestampFn = typeof options.timestamp === 'function' ? options.timestamp : exports.timestamp,
- timestamp = options.timestamp ? timestampFn() : null,
- meta = options.meta ? exports.clone(options.meta) : null,
- output;
-
- if (options.json) {
- output = meta || {};
- output.level = options.level;
- output.message = options.message;
-
- if (timestamp) {
- output.timestamp = timestamp;
- }
-
- return JSON.stringify(output);
- }
-
- output = timestamp ? timestamp + ' - ' : '';
- output += options.colorize ? config.colorize(options.level) : options.level;
- output += (': ' + options.message);
-
- if (meta && typeof meta === 'object' && Object.keys(meta).length > 0) {
- output += ' ' + loggly.serialize(meta);
- }
-
- return output;
-}; |
function hash (str)- -@str {string} String to hash.- -Utility function for creating unique ids -e.g. Profiling incoming HTTP requests on the same tick | exports.hash = function (str) {
- return crypto.createHash('sha1').update(str).digest('hex');
-}; |
Borrowed from node.js core- -I wanted a universal lowercase header message, as opposed to the | var months = ['Jan', 'Feb', 'Mar', 'Apr',
- 'May', 'Jun', 'Jul', 'Aug',
- 'Sep', 'Oct', 'Nov', 'Dec']; |
function pad (n)- -Returns a padded string if | exports.pad = function (n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
-}; |
function timestamp ()- -Returns a timestamp string for the current time. | exports.timestamp = function () {
- var d = new Date();
- var time = [
- exports.pad(d.getHours()),
- exports.pad(d.getMinutes()),
- exports.pad(d.getSeconds())
- ].join(':');
-
- return [d.getDate(), months[d.getMonth()], time].join(' ');
-};
-
- |
config.js | |
---|---|
/*
- * config.js: Default settings for all levels that winston knows about
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- *
- */
-
-var colors = require('colors');
-
-var config = exports,
- allColors = exports.allColors = {};
-
-config.addColors = function (colors) {
- mixin(allColors, colors);
-};
-
-config.colorize = function (level) {
- return level[allColors[level]];
-}; | |
Export config sets | config.cli = require('./config/cli-config');
-config.npm = require('./config/npm-config');
-config.syslog = require('./config/syslog-config'); |
Add colors for pre-defined config sets | config.addColors(config.npm.colors);
-config.addColors(config.syslog.colors);
-
-function mixin (target) {
- var args = Array.prototype.slice.call(arguments, 1);
-
- args.forEach(function (a) {
- var keys = Object.keys(a);
- for (var i = 0; i < keys.length; i++) {
- target[keys[i]] = a[keys[i]];
- }
- });
- return target;
-};
-
- |
cli-config.js | |
---|---|
/*
- * cli-config.js: Config that conform to commonly used CLI logging levels.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- *
- */
-
-var cliConfig = exports;
-
-cliConfig.levels = {
- silly: 0,
- input: 1,
- verbose: 2,
- prompt: 3,
- info: 4,
- data: 5,
- help: 6,
- warn: 7,
- debug: 8,
- error: 9
-};
-
-cliConfig.colors = {
- silly: 'magenta',
- input: 'grey',
- verbose: 'cyan',
- prompt: 'grey',
- info: 'green',
- data: 'grey',
- help: 'cyan',
- warn: 'yellow',
- debug: 'blue',
- error: 'red'
-};
-
- |
npm-config.js | |
---|---|
/*
- * npm-config.js: Config that conform to npm logging levels.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- *
- */
-
-var npmConfig = exports;
-
-npmConfig.levels = {
- silly: 0,
- verbose: 1,
- info: 2,
- warn: 3,
- debug: 4,
- error: 5
-};
-
-npmConfig.colors = {
- silly: 'magenta',
- verbose: 'cyan',
- info: 'green',
- warn: 'yellow',
- debug: 'blue',
- error: 'red'
-};
-
- |
syslog-config.js | |
---|---|
/*
- * syslog-config.js: Config that conform to syslog logging levels.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- *
- */
-
-var syslogConfig = exports;
-
-syslogConfig.levels = {
- debug: 0,
- info: 1,
- notice: 2,
- warning: 3,
- error: 4,
- crit: 5,
- alert: 6,
- emerg: 7
-};
-
-syslogConfig.colors = {
- debug: 'blue',
- info: 'green',
- notice: 'yellow',
- warning: 'red',
- error: 'red',
- crit: 'red',
- alert: 'yellow',
- emerg: 'red'
-};
-
- |
exception.js | |
---|---|
/*
- * exception.js: Utility methods for gathing information about uncaughtExceptions.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- *
- */
-
-var os = require('os'),
- stackTrace = require('stack-trace');
-
-var exception = exports;
-
-exception.getAllInfo = function (err) {
- return {
- process: exception.getProcessInfo(),
- os: exception.getOsInfo(),
- trace: exception.getTrace(err)
- };
-};
-
-exception.getProcessInfo = function () {
- return {
- pid: process.pid,
- uid: process.getuid(),
- gid: process.getgid(),
- cwd: process.cwd(),
- execPath: process.execPath,
- version: process.version,
- argv: process.argv,
- memoryUsage: process.memoryUsage()
- };
-};
-
-exception.getOsInfo = function () {
- return {
- loadavg: os.loadavg(),
- uptime: os.uptime()
- };
-};
-
-exception.getTrace = function (err) {
- var trace = err ? stackTrace.parse(err) : stackTrace.get();
- return trace.map(function (site) {
- return {
- column: site.getColumnNumber(),
- file: site.getFileName(),
- function: site.getFunctionName(),
- line: site.getLineNumber(),
- method: site.getMethodName(),
- native: site.isNative(),
- }
- });
-};
-
- |
logger.js | |
---|---|
/*
- * logger.js: Core logger object used by winston.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- *
- */
-
-var events = require('events'),
- util = require('util'),
- async = require('async'),
- config = require('./config'),
- common = require('./common'),
- exception = require('./exception');
-
-function capitalize(str) {
- return str && str[0].toUpperCase() + str.slice(1);
-} | |
Time constants | var ticksPerMillisecond = 10000; |
function Logger (options)- -@options {Object} Options for this instance.- -Constructor function for the Logger object responsible -for persisting log messages and metadata to one or more transports. | var Logger = exports.Logger = function (options) {
- events.EventEmitter.call(this);
- options = options || {};
-
- var self = this,
- handleExceptions = false;
- |
Set Levels and default logging level | this.padLevels = options.padLevels || false;
- this.setLevels(options.levels);
- |
Setup other intelligent default settings. | this.level = options.level || 'info';
- this.emitErrs = options.emitErrs || false;
- this.stripColors = options.stripColors || false;
- this.transports = {};
- this.exceptionHandlers = {};
- this.profilers = {};
- this._names = [];
- this._hnames = [];
-
- if (options.transports) {
- options.transports.forEach(function (transport) {
- self.add(transport, null, true);
-
- if (transport.handleExceptions) {
- handleExceptions = true;
- }
- });
- }
-
- if (options.exceptionHandlers) {
- options.exceptionHandlers.forEach(function (handler) {
- self._hnames.push(handler.name);
- self.exceptionHandlers[handler.name] = handler;
- });
- }
-
- if (options.handleExceptions || handleExceptions) {
- this.handleExceptions();
- }
-}; |
Inherit from | util.inherits(Logger, events.EventEmitter); |
function extend (target)- -@target {Object} Target to extend.- -Extends the target object with a 'log' method -along with a method for each level in this instance. | Logger.prototype.extend = function (target) {
- var self = this;
- ['log', 'profile'].concat(Object.keys(this.levels)).forEach(function (method) {
- target[method] = function () {
- return self[method].apply(self, arguments);
- };
- });
-
- return this;
-}; |
function log (level, msg, [meta], callback)- -@level {string} Level at which to log the message.- -@msg {string} Message to log- -@meta {Object} Optional Additional metadata to attach- -@callback {function} Continuation to respond to when complete.- -Core logging method exposed to Winston. Metadata is optional. | Logger.prototype.log = function (level, msg) {
- var self = this,
- callback,
- meta;
-
- if (arguments.length === 3) {
- if (typeof arguments[2] === 'function') {
- meta = {};
- callback = arguments[2];
- }
- else if (typeof arguments[2] === 'object') {
- meta = arguments[2];
- }
- }
- else if (arguments.length === 4) {
- meta = arguments[2];
- callback = arguments[3];
- } |
If we should pad for levels, do so | if (this.padLevels) {
- msg = new Array(this.levelLength - level.length).join(' ') + msg;
- }
-
- function onError (err) {
- if (callback) {
- callback(err);
- }
- else if (self.emitErrs) {
- self.emit('error', err);
- };
- }
-
- if (this.transports.length === 0) {
- return onError(new Error('Cannot log with no transports.'));
- }
- else if (typeof self.levels[level] === 'undefined') {
- return onError(new Error('Unknown log level: ' + level));
- }
- |
For consideration of terminal 'color" programs like colors.js,
-which can add ANSI escape color codes to strings, we destyle the
-ANSI color escape codes when see: http://en.wikipedia.org/wiki/ANSIescapecode | if (this.stripColors) {
- var code = /\u001b\[\d+m/g;
- msg = ('' + msg).replace(code, '');
- }
-
- for (var i = 0, l = this._names.length; i < l; i++) {
- var transport = this.transports[this._names[i]];
- if ((transport.level && self.levels[transport.level] <= self.levels[level])
- || (!transport.level && self.levels[self.level] <= self.levels[level])) {
- transport.log(level, msg, meta, function (err) {
- self.emit('logging', transport, level, msg, meta);
- });
- }
- }
- |
Immediately respond to the callback | if (callback) {
- callback(null, level, msg, meta);
- }
-
- return this;
-}; |
function handleExceptions ()- -Handles | Logger.prototype.handleExceptions = function () {
- var args = Array.prototype.slice.call(arguments),
- handlers = [],
- self = this;
-
- args.forEach(function (a) {
- if (Array.isArray(a)) {
- handlers = handlers.concat(a);
- }
- else {
- handlers.push(a);
- }
- });
-
- handlers.forEach(function (handler) {
- self.exceptionHandlers[handler.name] = handler;
- });
-
- this._hnames = Object.keys(self.exceptionHandlers);
-
- if (!this.catchExceptions) {
- this.catchExceptions = this._uncaughtException.bind(this);
- process.on('uncaughtException', this.catchExceptions);
- }
-}; |
function unhandleExceptions ()- -Removes any handlers to | Logger.prototype.unhandleExceptions = function () {
- var self = this;
-
- if (this.catchExceptions) {
- Object.keys(this.exceptionHandlers).forEach(function (name) {
- if (handler.close) {
- handler.close();
- }
- });
-
- this.exceptionHandlers = {};
- Object.keys(this.transports).forEach(function (name) {
- var transport = self.transports[name];
- if (transport.handleExceptions) {
- transport.handleExceptions = false;
- }
- })
-
- process.removeListener('uncaughtException', this.catchExceptions);
- this.catchExceptions = false;
- }
-}; |
function add (transport, [options])- -@transport {Transport} Prototype of the Transport object to add.- -@options {Object} Optional Options for the Transport to add.- -@instance {Boolean} Optional Value indicating if
-
- | Logger.prototype.add = function (transport, options, created) {
- var instance = created ? transport : (new (transport)(options));
-
- if (!instance.name && !instance.log) {
- throw new Error('Unknown transport with no log() method');
- }
- else if (this.transports[instance.name]) {
- throw new Error('Transport already attached: ' + instance.name);
- }
-
- this.transports[instance.name] = instance;
- this._names = Object.keys(this.transports);
- |
Listen for the | instance._onError = this._onError.bind(this, instance)
- instance.on('error', instance._onError);
-
- return this;
-}; |
function remove (transport)- -@transport {Transport} Transport to remove.- -Removes a transport of the specified type from this instance. | Logger.prototype.remove = function (transport) {
- var name = transport.name || transport.prototype.name;
-
- if (!this.transports[name]) {
- throw new Error('Transport ' + name + ' not attached to this instance');
- }
-
- var instance = this.transports[name];
- delete this.transports[name];
- this._names = Object.keys(this.transports);
-
- if (instance.close) {
- instance.close();
- }
-
- instance.removeListener('error', instance._onError);
- return this;
-}; |
function profile (id, [msg, meta, callback])- -@id {string} Unique id of the profiler- -@msg {string} Optional Message to log- -@meta {Object} Optional Additional metadata to attach- -@callback {function} Optional Continuation to respond to when complete.- -Tracks the time inbetween subsequent calls to this method
-with the same | Logger.prototype.profile = function (id) {
- var now = Date.now(), then, args,
- msg, meta, callback;
-
- if (this.profilers[id] && arguments.length !== 1) {
- then = this.profilers[id];
- delete this.profilers[id];
- |
Support variable arguments: msg, meta, callback | args = Array.prototype.slice.call(arguments);
- callback = typeof args[args.length - 1] === 'function' ? args.pop() : null;
- meta = typeof args[args.length - 1] === 'object' ? args.pop() : {};
- msg = args.length === 2 ? args[1] : id;
- |
Set the duration property of the metadata | meta.duration = now - then + 'ms';
- return this.info(msg, meta, callback);
- }
- else {
- this.profilers[id] = now;
- }
-
- return this;
-}; |
function setLevels (target)- -@target {Object} Target levels to use on this instance- -Sets the | Logger.prototype.setLevels = function (target) {
- return common.setLevels(this, this.levels, target);
-}; |
function cli ()- -Configures this instance to have the default -settings for command-line interfaces: no timestamp, -colors enabled, padded output, and additional levels. | Logger.prototype.cli = function () {
- this.padLevels = true;
- this.setLevels(config.cli.levels);
- config.addColors(config.cli.colors);
-
- if (this.transports.console) {
- this.transports.console.colorize = true;
- this.transports.console.timestamp = false;
- }
-
- return this;
-}; |
@private function _uncaughtException (err)- -@err {Error} Error to handle- -Logs all relevant information around the | Logger.prototype._uncaughtException = function (err) {
- var self = this,
- responded = false,
- info = exception.getAllInfo(err),
- handlers = this._getExceptionHandlers(),
- timeout;
-
- function logAndWait (transport, next) {
- transport.logException('uncaughtException', info, next);
- }
-
- function gracefulExit () {
- if (!responded) { |
Remark: Currently ignoring any exceptions from transports - when catching uncaught exceptions. | clearTimeout(timeout);
- responded = true;
- process.exit(1);
- }
- }
-
- if (!handlers || handlers.length === 0) {
- return gracefulExit();
- }
- |
Log to all transports and allow the operation to take
-only up to | async.forEach(handlers, logAndWait, gracefulExit);
- timeout = setTimeout(gracefulExit, 3000);
-}; |
@private function _getExceptionHandlers ()- -Returns the list of transports and exceptionHandlers -for this instance. | Logger.prototype._getExceptionHandlers = function () {
- var self = this;
-
- return this._hnames.map(function (name) {
- return self.exceptionHandlers[name];
- }).concat(this._names.map(function (name) {
- return self.transports[name].handleExceptions && self.transports[name];
- })).filter(Boolean);
-}; |
@private function _onError (transport, err)- -@transport {Object} Transport on which the error occured- -@err {Error} Error that occurred on the transport- -Bubbles the error, | Logger.prototype._onError = function (transport, err) {
- if (self.emitErrs) {
- self.emit('error', err, transport);
- }
-};
-
- |
transports.js | |
---|---|
/*
- * transports.js: Set of all transports Winston knows about
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- *
- */
-
-var fs = require('fs'),
- path = require('path');
-
-var transports = exports;
-
-function capitalize (str) {
- return str && str[0].toUpperCase() + str.slice(1);
-}; | |
Setup all transports as lazy-loaded getters. | fs.readdirSync(path.join(__dirname, 'transports')).forEach(function (file) {
- var transport = file.replace('.js', ''),
- name = capitalize(transport);
-
- if (transport === 'transport') {
- return;
- }
-
- transports.__defineGetter__(name, function () {
- return require('./transports/' + transport)[name];
- });
-});
-
- |
console.js | |
---|---|
/*
- * console.js: Transport for outputting to the console
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- *
- */
-
-var events = require('events'),
- util = require('util'),
- colors = require('colors'),
- common = require('../common'),
- Transport = require('./transport').Transport; | |
function Console (options)- -@options {Object} Options for this instance.- -Constructor function for the Console transport object responsible -for persisting log messages and metadata to a terminal or TTY. | var Console = exports.Console = function (options) {
- Transport.call(this, options);
- options = options || {};
-
- this.name = 'console';
- this.json = options.json || false;
- this.colorize = options.colorize || false;
- this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false;
-}; |
Inherit from | util.inherits(Console, Transport); |
Expose the name of this Transport on the prototype | Console.prototype.name = 'console'; |
function log (level, msg, [meta], callback)- -@level {string} Level at which to log the message.- -@msg {string} Message to log- -@meta {Object} Optional Additional metadata to attach- -@callback {function} Continuation to respond to when complete.- -Core logging method exposed to Winston. Metadata is optional. | Console.prototype.log = function (level, msg, meta, callback) {
- if (this.silent) {
- return callback(null, true);
- }
-
- var self = this, output = common.log({
- level: level,
- message: msg,
- meta: meta,
- colorize: this.colorize,
- timestamp: this.timestamp
- });
-
- if (level === 'error' || level === 'debug') {
- util.error(output);
- }
- else {
- util.puts(output);
- } |
Emit the | self.emit('logged');
- callback(null, true);
-};
-
- |
couchdb.js | |
---|---|
/*
- * Couchdb.js: Transport for logging to Couchdb
- *
- * (C) 2011 Max Ogden
- * MIT LICENSE
- *
- */
-
-var events = require('events'),
- http = require('http'),
- util = require('util'),
- common = require('../common'),
- Transport = require('./transport').Transport; | |
function Couchdb (options)- -@options {Object} Options for this instance.- -Constructor function for the Console transport object responsible -for making arbitrary HTTP requests whenever log messages and metadata -are received. | var Couchdb = exports.Couchdb = function (options) {
- Transport.call(this, options);
-
- this.name = 'Couchdb';
- this.db = options.db;
- this.user = options.user;
- this.pass = options.pass;
- this.host = options.host || 'localhost';
- this.port = options.port || 5984;
-
- if (options.auth) { |
TODO: add http basic auth options for outgoing HTTP requests | }
-
- if (options.ssl) { |
TODO: add ssl support for outgoing HTTP requests | }
-}; |
Inherit from | util.inherits(Couchdb, Transport); |
Expose the name of this Transport on the prototype | Couchdb.prototype.name = 'Couchdb'; |
function log (level, msg, [meta], callback)- -@level {string} Level at which to log the message.- -@msg {string} Message to log- -@meta {Object} Optional Additional metadata to attach- -@callback {function} Continuation to respond to when complete.- -Core logging method exposed to Winston. Metadata is optional. | Couchdb.prototype.log = function (level, msg, meta, callback) {
- if (this.silent) {
- return callback(null, true);
- }
-
- var self = this,
- message = common.clone(meta),
- options,
- req;
-
- message.level = level;
- message.message = msg; |
Prepare options for outgoing HTTP request | options = {
- host: this.host,
- port: this.port,
- path: "/" + this.db,
- method: "POST",
- headers: {"content-type": "application/json"}
- };
-
- if (options.user && options.pass) {
- options.headers["Authorization"] = "Basic " + new Buffer(options.user + ":" + options.pass).toString('base64');
- }
- |
Perform HTTP logging request | req = http.request(options, function (res) { |
No callback on request, fire and forget about the response | self.emit('logged', res);
- });
-
- req.on('error', function (err) { |
Propagate the | self.emit('error', err);
- });
- |
Write logging event to the outgoing request body | req.write(JSON.stringify({
- method: 'log',
- params: {
- timestamp: new Date(), // RFC3339/ISO8601 format instead of common.timestamp()
- msg: msg,
- level: level,
- meta: meta
- }
- }));
-
- req.end();
- |
Always return true, regardless of any errors | callback(null, true);
-};
-
- |
file.js | |
---|---|
/*
- * file.js: Transport for outputting to a local log file
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- *
- */
-
-var events = require('events'),
- fs = require('fs'),
- path = require('path'),
- util = require('util'),
- colors = require('colors'),
- common = require('../common'),
- Transport = require('./transport').Transport;
- | |
function File (options)- -@options {Object} Options for this instance.- -Constructor function for the File transport object responsible -for persisting log messages and metadata to one or more files. | var File = exports.File = function (options) {
- Transport.call(this, options);
- |
Helper function which throws an | function throwIf (target /*, illegal... */) {
- Array.prototype.slice.call(arguments, 1).forEach(function (name) {
- if (options[name]) {
- throw new Error('Cannot set ' + name + ' and ' + target + 'together');
- }
- });
- }
-
- if (options.filename || options.dirname) {
- throwIf('filename or dirname', 'stream');
- this._basename = this.filename = path.basename(options.filename) || 'winston.log';
- this.dirname = options.dirname || path.dirname(options.filename);
- this.options = options.options || { flags: 'a' };
- }
- else if (options.stream) {
- throwIf('stream', 'filename', 'maxsize');
- this.stream = options.stream;
- }
- else {
- throw new Error('Cannot log to file without filename or stream.');
- }
-
- this.json = options.json !== false;
- this.colorize = options.colorize || false;
- this.maxsize = options.maxsize || null;
- this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false; |
Internal state variables representing the number -of files this instance has created and the current -size (in bytes) of the current logfile. | this._size = 0;
- this._created = 0;
- this._buffer = [];
-}; |
Inherit from | util.inherits(File, Transport); |
Expose the name of this Transport on the prototype | File.prototype.name = 'file'; |
function log (level, msg, [meta], callback)- -@level {string} Level at which to log the message.- -@msg {string} Message to log- -@meta {Object} Optional Additional metadata to attach- -@callback {function} Continuation to respond to when complete.- -Core logging method exposed to Winston. Metadata is optional. | File.prototype.log = function (level, msg, meta, callback) {
- if (this.silent) {
- return callback(null, true);
- }
-
- var self = this, output = common.log({
- level: level,
- message: msg,
- meta: meta,
- json: this.json,
- colorize: this.colorize,
- timestamp: this.timestamp
- }) + '\n';
-
- this._size += output.length;
-
- function onDrain () {
- self.emit('logged');
- }
-
- if (!this.filename) { |
If there is no | this.stream.write(output);
- this.stream.once('drain', onDrain);
- }
- else {
- this.open(function (err) {
- if (err) { |
If there was an error enqueue the message | return self._buffer.push(output);
- }
-
- self.stream.write(output);
- self.stream.once('drain', onDrain);
- });
- }
-
- callback(null, true);
-}; |
function open (callback)- -@callback {function} Continuation to respond to when complete- -Checks to see if a new file needs to be created based on the | File.prototype.open = function (callback) {
- if (this.opening) { |
If we are already attempting to open the next -available file then respond with a value indicating -that the message should be buffered. | return callback(true);
- }
- else if (!this.stream || (this.maxsize && this._size >= this.maxsize)) { |
If we dont have a stream or have exceeded our size, then create -the next stream and respond with a value indicating that -the message should be buffered. | callback(true);
- return this._createStream();
- }
- |
Otherwise we have a valid (and ready) stream. | callback();
-}; |
function close ()- -Closes the stream associated with this instance. | File.prototype.close = function() {
- var self = this;
-
- if (this.stream) {
- this.stream.end();
- this.stream.destroySoon();
-
- this.stream.once('drain', function () {
- self.emit('flush');
- self.emit('closed');
- });
- }
-}; |
function flush ()- -Flushes any buffered messages to the current | File.prototype.flush = function () {
- var self = this; |
Iterate over the | this._buffer.forEach(function (str) {
- process.nextTick(function () {
- self.stream.write(str);
- self._size += str.length;
- });
- });
- |
Quickly truncate the | self._buffer.length = 0;
- |
When the stream has drained we have flushed -our buffer. | self.stream.once('drain', function () {
- self.emit('flush');
- self.emit('logged');
- });
-}; |
@private function _createStream ()- -Attempts to open the next appropriate file for this instance
-based on the common state (such as | File.prototype._createStream = function () {
- var self = this;
- this.opening = true;
-
- (function checkFile (target) {
- var fullname = path.join(self.dirname, target);
- |
Creates the | function createAndFlush (size) {
- if (self.stream) {
- self.stream.end();
- self.stream.destroySoon();
- }
-
- self._size = size;
- self.filename = target;
- self.stream = fs.createWriteStream(fullname, self.options);
- |
When the current stream has finished flushing
-then we can be sure we have finished opening
-and thus can emit the | self.once('flush', function () {
- self.opening = false;
- self.emit('open', fullname);
- }); |
Remark: It is possible that in the time it has taken to find the
-next logfile to be written more data than | self.flush();
- }
-
- fs.stat(fullname, function (err, stats) {
- if (err) {
- if (err.code !== 'ENOENT') {
- return self.emit('error', err);
- }
-
- return createAndFlush(0);
- }
-
- if (!stats || (self.maxsize && stats.size >= self.maxsize)) { |
If | return checkFile(self._getFile(true));
- }
-
- createAndFlush(stats.size);
- });
- })(this._getFile());
-}; |
@private function _getFile ()- -Gets the next filename to use for this instance -in the case that log filesizes are being capped. | File.prototype._getFile = function (inc) {
- var self = this,
- ext = path.extname(this._basename),
- basename = path.basename(this._basename, ext);
-
- if (inc) { |
Increment the number of files created or -checked by this instance. | this._created += 1;
- }
-
- return this._created
- ? basename + this._created + ext
- : basename + ext;
-};
-
- |
loggly.js | |
---|---|
/*
- * loggly.js: Transport for logginh to remote Loggly API
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- *
- */
-
-var events = require('events'),
- loggly = require('loggly'),
- util = require('util'),
- async = require('async'),
- common = require('../common'),
- Transport = require('./transport').Transport; | |
function Loggly (options)- -@options {Object} Options for this instance.- -Constructor function for the Loggly transport object responsible -for persisting log messages and metadata to Loggly; 'LaaS'. | var Loggly = exports.Loggly = function (options) {
- Transport.call(this, options);
-
- if (!options.subdomain) {
- throw new Error('Loggly Subdomain is required');
- }
-
- if (!options.inputToken && !options.inputName) {
- throw new Error('Target input token or name is required.');
- }
-
- if (!options.auth && options.inputName) {
- throw new Error('Loggly authentication is required');
- }
-
- this.name = 'loggly';
- this.logBuffer = [];
-
- this.client = loggly.createClient({
- subdomain: options.subdomain,
- auth: options.auth || null,
- json: options.json || false
- });
-
- if (options.inputToken) {
- this.inputToken = options.inputToken;
- this.ready = true;
- }
- else if (options.inputName) {
- this.ready = false;
- this.inputName = options.inputName;
-
- var self = this;
- this.client.getInput(this.inputName, function (err, input) {
- if (err) {
- throw err;
- }
-
- self.inputToken = input.input_token;
- self.ready = true;
- });
- }
-}; |
Inherit from | util.inherits(Loggly, Transport); |
Expose the name of this Transport on the prototype | Loggly.prototype.name = 'loggly'; |
function log (level, msg, [meta], callback)- -@level {string} Level at which to log the message.- -@msg {string} Message to log- -@meta {Object} Optional Additional metadata to attach- -@callback {function} Continuation to respond to when complete.- -Core logging method exposed to Winston. Metadata is optional. | Loggly.prototype.log = function (level, msg, meta, callback) {
- if (this.silent) {
- return callback(null, true);
- }
-
- var self = this,
- message = common.clone(meta);
-
- message.level = level;
- message.message = msg;
-
- if (!this.ready) { |
If we haven't gotten the input token yet -add this message to the log buffer. | this.logBuffer.push(message);
- }
- else if (this.ready && this.logBuffer.length > 0) { |
Otherwise if we have buffered messages -add this message to the buffer and flush them. | this.logBuffer.push(message);
- this.flush();
- }
- else { |
Otherwise just log the message as normal | this.client.log(this.inputToken, message, function () {
- self.emit('logged');
- });
- }
-
- callback(null, true);
-}; |
function flush ()- -Flushes any buffered messages to the current | Loggly.prototype.flush = function () {
- var self = this;
-
- function logMsg (msg, next) {
- self.client.log(self.inputToken, msg, function (err) {
- if (err) {
- self.emit('error', err);
- }
-
- next();
- });
- }
- |
Initiate calls to loggly for each message in the buffer | async.forEach(this.logBuffer, logMsg, function () {
- self.emit('logged');
- });
-
- process.nextTick(function () { |
Then quickly truncate the list | self.logBuffer.length = 0;
- });
-};
-
- |
transport.js | |
---|---|
/*
- * transport.js: Base Transport object for all Winston transports.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- *
- */
-
-var events = require('events'),
- util = require('util'); | |
function Transport (options)- -@options {Object} Options for this instance.- -Constructor function for the Tranport object responsible -base functionality for all winston transports. | var Transport = exports.Transport = function (options) {
- events.EventEmitter.call(this);
-
- options = options || {};
- this.level = options.level || 'info';
- this.silent = options.silent || false;
- this.handleExceptions = options.handleExceptions || false;
-}; |
Inherit from | util.inherits(Transport, events.EventEmitter); |
function logException (msg, meta, callback)- -@msg {string} Message to log- -@meta {Object} Optional Additional metadata to attach- -@callback {function} Continuation to respond to when complete.- -Logs the specified | Transport.prototype.logException = function (msg, meta, callback) {
- var self = this;
-
- function onLogged () {
- self.removeListener('error', onError);
- callback();
- }
-
- function onError () {
- self.removeListener('logged', onLogged);
- callback();
- }
-
- this.once('logged', onLogged);
- this.once('error', onError);
- this.log('error', msg, meta, function () { });
-};
-
- |
webhook.js | |
---|---|
/*
- * webhook.js: Transport for logging to remote http endpoints ( POST / RECEIVE webhooks )
- *
- * (C) 2011 Marak Squires
- * MIT LICENCE
- *
- */
-
-var events = require('events'),
- http = require('http'),
- util = require('util'),
- common = require('../common'),
- Transport = require('./transport').Transport; | |
function WebHook (options)- -@options {Object} Options for this instance.- -Constructor function for the Console transport object responsible -for making arbitrary HTTP requests whenever log messages and metadata -are received. | var Webhook = exports.Webhook = function (options) {
- Transport.call(this, options);
-
- this.name = 'webhook';
- this.host = options.host || 'localhost';
- this.port = options.port || 8080;
- this.method = options.method || 'POST';
- this.path = options.path || '/winston-log';
-
- if (options.auth) { |
TODO: add http basic auth options for outgoing HTTP requests | }
-
- if (options.ssl) { |
TODO: add ssl support for outgoing HTTP requests | }
-}; |
Inherit from | util.inherits(Webhook, Transport); |
Expose the name of this Transport on the prototype | Webhook.prototype.name = 'webhook'; |
function log (level, msg, [meta], callback)- -@level {string} Level at which to log the message.- -@msg {string} Message to log- -@meta {Object} Optional Additional metadata to attach- -@callback {function} Continuation to respond to when complete.- -Core logging method exposed to Winston. Metadata is optional. | Webhook.prototype.log = function (level, msg, meta, callback) {
- if (this.silent) {
- return callback(null, true);
- }
-
- var self = this,
- message = common.clone(meta),
- options,
- req;
-
- message.level = level;
- message.message = msg; |
Prepare options for outgoing HTTP request | options = {
- host: this.host,
- port: this.port,
- path: this.path,
- method: this.method
- };
- |
Perform HTTP logging request | req = http.request(options, function (res) { |
No callback on request, fire and forget about the response | self.emit('logged');
- });
-
- req.on('error', function (err) { |
Propagate the | self.emit('error', err);
- });
- |
Write logging event to the outgoing request body - -jsonMessage is currently conforming to JSON-RPC v1.0, -but without the unique id since there is no anticipated response -see: http://en.wikipedia.org/wiki/JSON-RPC | req.write(JSON.stringify({
- method: 'log',
- params: {
- timestamp: common.timestamp(),
- msg: msg,
- level: level,
- meta: meta
- }
- }));
-
- req.end();
- |
Always return true, regardless of any errors | callback(null, true);
-};
-
- |
loggly.js | |
---|---|
/*
- * loggly.js: Wrapper for node-loggly object
- *
- * (C) 2010 Nodejitsu Inc.
- * MIT LICENSE
- *
- */
-
-var loggly = exports; | |
Export node-loggly core client APIs | loggly.createClient = require('./loggly/core').createClient;
-loggly.Loggly = require('./loggly/core').Loggly;
-loggly.Config = require('./loggly/config').Config; |
Export Resources for node-loggly | loggly.Input = require('./loggly/input').Input;
-loggly.Facet = require('./loggly/facet').Facet;
-loggly.Device = require('./loggly/device').Device;
-loggly.Search = require('./loggly/search').Search;
-
- |
common.js | |
---|---|
/*
- * common.js: Common utility functions for requesting against Loggly APIs
- *
- * (C) 2010 Nodejitsu Inc.
- * MIT LICENSE
- *
- */
-
-var request = require('request'),
- loggly = require('../loggly');
-
-var common = exports; | |
Failure HTTP Response codes based -off Loggly specification. | var failCodes = common.failCodes = {
- 400: "Bad Request",
- 401: "Unauthorized",
- 403: "Forbidden",
- 404: "Not Found",
- 409: "Conflict / Duplicate",
- 410: "Gone",
- 500: "Internal Server Error",
- 501: "Not Implemented",
- 503: "Throttled"
-}; |
Success HTTP Response codes based -off Loggly specification. | var successCodes = common.successCodes = {
- 200: "OK",
- 201: "Created",
- 202: "Accepted",
- 203: "Non-authoritative information",
- 204: "Deleted",
-}; |
Core method that actually sends requests to Loggly. -This method is designed to be flexible w.r.t. arguments -and continuation passing given the wide range of different -requests required to fully implement the Loggly API. - -Continuations: - 1. 'callback': The callback passed into every node-loggly method - 2. 'success': A callback that will only be called on successful requests. - This is used throughout node-loggly to conditionally - do post-request processing such as JSON parsing. - -Possible Arguments (1 & 2 are equivalent): - 1. common.loggly('some-fully-qualified-url', auth, callback, success) - 2. common.loggly('GET', 'some-fully-qualified-url', auth, callback, success) - 3. common.loggly('DELETE', 'some-fully-qualified-url', auth, callback, success) - 4. common.loggly({ method: 'POST', uri: 'some-url', body: { some: 'body'} }, callback, success) | common.loggly = function () {
- var args = Array.prototype.slice.call(arguments),
- success = args.pop(),
- callback = args.pop(),
- requestBody,
- headers,
- method,
- auth,
- uri;
- |
Now that we've popped off the two callbacks -We can make decisions about other arguments | if (args.length == 1) {
- if (typeof args[0] === 'string') { |
If we got a string assume that it's the URI | method = 'GET';
- uri = args[0];
- }
- else {
- method = args[0]['method'] || 'GET',
- uri = args[0]['uri'];
- requestBody = args[0]['body'];
- auth = args[0]['auth'];
- headers = args[0]['headers'];
- }
- }
- else if (args.length == 2) {
- method = 'GET';
- uri = args[0];
- auth = args[1];
- }
- else {
- method = args[0];
- uri = args[1];
- auth = args[2];
- }
-
- function onError (err) {
- if (callback) {
- callback(err);
- }
- }
-
- var requestOptions = {
- uri: uri,
- method: method,
- headers: headers || {}
- };
-
- if (auth) {
- requestOptions.headers['authorization'] = 'Basic ' + new Buffer(auth.username + ':' + auth.password).toString('base64');
- }
-
- if (requestBody) {
- requestOptions.body = requestBody;
- }
-
- try {
- request(requestOptions, function (err, res, body) {
- if (err) {
- return onError(err);
- }
-
- var statusCode = res.statusCode.toString();
- if (Object.keys(failCodes).indexOf(statusCode) !== -1) {
- return onError((new Error('Loggly Error (' + statusCode + '): ' + failCodes[statusCode])));
- }
-
- success(res, body);
- });
- }
- catch (ex) {
- onError(ex);
- }
-}; |
function clone (obj) - Helper method for deep cloning pure JSON objects - i.e. JSON objects that are either literals or objects (no Arrays, etc) | common.clone = function (obj) {
- var clone = {};
- for (var i in obj) {
- clone[i] = obj[i] instanceof Object ? common.clone(obj[i]) : obj[i];
- }
-
- return clone;
-};
-
- |
config.js | |
---|---|
/*
- * config.js: Configuration information for your Loggly account.
- * This information is only used for require('loggly')./\.+/ methods
- *
- * (C) 2010 Nodejitsu Inc.
- * MIT LICENSE
- *
- */ | |
function createConfig (defaults) - Creates a new instance of the configuration - object based on default values | exports.createConfig = function (defaults) {
- return new Config(defaults);
-}; |
Config (defaults) - Constructor for the Config object | var Config = exports.Config = function (defaults) {
- if (!defaults.subdomain) {
- throw new Error('Subdomain is required to create an instance of Config');
- }
-
- this.subdomain = defaults.subdomain;
- this.json = defaults.json || null;
- this.auth = defaults.auth || null;
-};
-
-Config.prototype = {
- get subdomain () {
- return this._subdomain;
- },
-
- set subdomain (value) {
- this._subdomain = value;
- },
-
- get logglyUrl () {
- return 'https://' + [this._subdomain, 'loggly', 'com'].join('.') + '/api';
- },
-
- get inputUrl () {
- return 'https://logs.loggly.com/inputs/';
- }
-};
-
- |
core.js | |
---|---|
/*
- * core.js: Core functions for accessing Loggly
- *
- * (C) 2010 Nodejitsu Inc.
- * MIT LICENSE
- *
- */
-
-var events = require('events'),
- qs = require('querystring'),
- config = require('./config'),
- common = require('./common'),
- Search = require('./search').Search,
- Facet = require('./facet').Facet,
- loggly = require('../loggly'); | |
function createClient (options) - Creates a new instance of a Loggly client. | exports.createClient = function (options) {
- return new Loggly(config.createConfig(options));
-}; |
Loggly (config) - Constructor for the Loggly object | var Loggly = exports.Loggly = function (config) {
- this.config = config;
-}; |
function log (callback) - logs args to input device | Loggly.prototype.log = function (inputId, msg, callback) {
- var emitter = new (events.EventEmitter)(),
- message;
-
- if (msg instanceof Object) {
- message = this.config.json ? JSON.stringify(msg) : qs.unescape(qs.stringify(msg, ','));
- } else {
- message = this.config.json ? JSON.stringify({ message : msg }) : msg;
- }
-
- var logOptions = {
- uri: this.config.inputUrl + inputId,
- method: 'POST',
- body: message,
- headers: {
- 'Content-Type': this.config.json ? 'application/json' : 'text/plain'
- }
- };
-
- common.loggly(logOptions, callback, function (res, body) {
- try {
- var result = JSON.parse(body);
- if (callback) {
- callback(null, result);
- }
-
- emitter.emit('log', result);
- }
- catch (ex) {
- if (callback) {
- callback(new Error('Unspecified error from Loggly: ' + ex));
- }
- }
- });
-
- return emitter;
-}; |
function search (query, callback) - Returns a new search object which can be chained - with options or called directly if @callback is passed - initially. - -Sample Usage: - -client.search('404') - .meta({ ip: '127.0.0.1' }) - .context({ rows: 100 }) - .run(function () { /* ... */ }); | Loggly.prototype.search = function (query, callback) {
- return new Search(query, this, callback);
-}; |
function facet (facet, query, [options], callback) - Performs a facet search against loggly with the - specified facet, query and options. | Loggly.prototype.facet = function (facet, query, callback) {
- return new Facet(facet, query, this, callback);
-}; |
function getInputs ([raw], callback) - Returns a list of all inputs for the authenicated account | Loggly.prototype.getInputs = function () {
- var self = this,
- args = Array.prototype.slice.call(arguments),
- callback = args.pop(),
- raw = args.length > 0 ? args[0] : false;
-
- common.loggly(this.logglyUrl('inputs'), this.config.auth, callback, function (res, body) {
- var inputs = [],
- results = JSON.parse(body);
-
- if (!raw) {
- results.forEach(function (result) {
- inputs.push(new (loggly.Input)(self, result));
- });
-
- return callback(null, inputs);
- }
-
- callback(null, results);
- });
-}; |
function getInput (name, callback) - Returns the input with the specified name | Loggly.prototype.getInput = function (name, callback) {
- var self = this;
- this.getInputs(true, function (err, results) {
- if (err) {
- return callback(err);
- }
-
- var matches = results.filter(function (r) { return r.name === name }),
- input = null;
-
- if (matches.length > 0) {
- input = new (loggly.Input)(self, matches[0]);
- }
-
- callback(null, input);
- });
-}; |
function addDevice (inputId, address, callback) - Adds the device at address to the input specified by inputId | Loggly.prototype.addDeviceToInput = function (inputId, address, callback) {
- var addOptions = {
- uri: this.logglyUrl('devices'),
- auth: this.config.auth,
- method: 'POST',
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded'
- },
- body: qs.stringify({ 'input_id': inputId, 'ip': address }).replace('"', '')
- };
-
- common.loggly(addOptions, callback, function (res, body) {
- callback(null, res);
- });
-}; |
function addDevice (inputId, callback) - Adds the calling device to the input | Loggly.prototype.addDevice = function (inputId, callback) { |
Remark: This is not fully implemented yet | callback(new Error('Not Implemented Yet...'));
- |
common.loggly(this.logglyUrl('inputs', inputId, 'adddevice'), this.config.auth, callback, function (res, body) { -}); | }; |
function getDevices (callback) - Returns a list of all devices for the authenicated account | Loggly.prototype.getDevices = function (callback) {
- var self = this;
- common.loggly(this.logglyUrl('devices'), this.config.auth, callback, function (res, body) {
- var results = JSON.parse(body),
- devices = [];
-
- results.forEach(function (result) {
- devices.push(new (loggly.Device)(self, result));
- });
-
- callback(null, devices);
- });
-}; |
function logglyUrl ([path, to, resource]) - Helper method that concats the string params into a url - to request against a loggly serverUrl. | Loggly.prototype.logglyUrl = function (/* path, to, resource */) {
- var args = Array.prototype.slice.call(arguments);
- return [this.config.logglyUrl].concat(args).join('/');
-};
-
- |
device.js | |
---|---|
/*
- * device.js: Instance of a single Loggly device
- *
- * (C) 2010 Nodejitsu Inc.
- * MIT LICENSE
- *
- */
-
-var Device = exports.Device = function (client, details) {
- if (!details) throw new Error("Device must be constructed with at least basic details.")
-
- this.client = client;
- this._setProperties(details);
-};
-
-Device.prototype.addToInput = function (inputId, callback) {
- this.client.addDeviceToInput(inputId, this.id, callback);
-};
- | |
Sets the properties for this instance -Parameters: details | Device.prototype._setProperties = function (details) { |
Copy the properties to this instance | var self = this;
- Object.keys(details).forEach(function (key) {
- self[key] = details[key];
- });
-};
-
- |
facet.js | |
---|---|
/*
- * facet.js: Chainable search functions for Loggly facet searches.
- *
- * (C) 2010 Nodejitsu Inc.
- * MIT LICENSE
- *
- */
-
-var util = require('util'),
- Search = require('./search').Search; | |
function Facet (facet, query, client, callback) - Chainable facet search object for Loggly API | var Facet = exports.Facet = function (facet, query, client, callback) {
- if (['date', 'ip', 'input'].indexOf(facet) === -1) {
- var error = new Error('Cannot search with unknown facet: ' + facet);
-
- if (callback) {
- return callback(error);
- }
- else {
- throw error;
- }
- }
- |
Set the baseUrl to be facet/:facet? | this.baseUrl = ['facets', facet + '?'].join('/');
- |
Call the base constructor. | Search.call(this, query, client, callback);
-}; |
Inherit from | util.inherits(Facet, Search);
-
- |
input.js | |
---|---|
/*
- * input.js: Instance of a single Loggly input
- *
- * (C) 2010 Nodejitsu Inc.
- * MIT LICENSE
- *
- */
-
-var Input = exports.Input = function (client, details) {
- if (!details) {
- throw new Error("Input must be constructed with at least basic details.");
- }
-
- this.client = client;
- this._setProperties(details);
-};
-
-Input.prototype.log = function (msg, callback) {
- return this.client.log(this.input_token, msg, callback);
-};
-
-Input.prototype.addDevice = function (address, callback) {
- this.client.addDeviceToInput(this.id, address, callback);
-};
- | |
Sets the properties for this instance -Parameters: details | Input.prototype._setProperties = function (details) { |
Copy the properties to this instance | var self = this;
- Object.keys(details).forEach(function (key) {
- self[key] = details[key];
- });
-};
-
- |
search.js | |
---|---|
/*
- * search.js: chainable search functions for Loggly
- *
- * (C) 2010 Nodejitsu Inc.
- * MIT LICENSE
- *
- */
-
-var qs = require('querystring'),
- timespan = require('timespan'),
- common = require('./common'); | |
function Search (query, client, callback) - Chainable search object for Loggly API | var Search = exports.Search = function (query, client, callback) {
- this.query = query;
- this.client = client;
-
- if (!this.baseUrl) {
- this.baseUrl = 'search?';
- }
- |
If we're passed a callback, run immediately. | if (callback) {
- this.callback = callback;
- this.run();
- }
-}; |
function meta (meta) - Sets the appropriate metadata for this search query: - e.g. ip, inputname | Search.prototype.meta = function (meta) {
- this._meta = meta;
- return this;
-}; |
function context (context) - Sets the appropriate context for this search query: - e.g. rows, start, from, until, order, format, fields | Search.prototype.context = function (context) {
- this._context = context;
- return this;
-}; |
function run (callback)- -@callback {function} Continuation to respond to when complete- -Runs the search query for for this instance with the query, metadata, -context, and other parameters that have been configured on it. | Search.prototype.run = function (callback) {
- var rangeError;
- |
Trim the search query | this.query.trim();
- |
Update the callback for this instance if it's passed | this.callback = callback || this.callback;
- if (!this.callback) {
- throw new Error('Cannot run search without a callback function.');
- }
- |
If meta was passed, update the search query appropriately | if (this._meta) {
- this.query += ' ' + qs.unescape(qs.stringify(this._meta, ' ', ':'));
- } |
Set the context for the query string | this._context = this._context || {};
- this._context.q = this.query;
- this._checkRange();
-
- var self = this, searchOptions = {
- uri: this.client.logglyUrl(this.baseUrl + qs.stringify(this._context)),
- auth: this.client.config.auth
- };
-
- common.loggly(searchOptions, this.callback, function (res, body) {
- self.callback(null, JSON.parse(body));
- });
-
- return this;
-}; |
function _checkRange ()- -Checks if the range that has been configured for this -instance is valid and updates if it is not. | Search.prototype._checkRange = function () {
- if (!this._context || (!this._context.until && !this._context.from)) {
- return;
- }
-
- this._context.until = this._context.until || 'NOW';
- this._context.from = this._context.from || 'NOW-24HOURS';
-
- if (!timespan.parseDate(this._context.until)) {
- this._context.until = 'NOW';
- }
-
- if (!timespan.parseDate(this._context.from)) {
- this._context.from = 'NOW-24HOURS';
- }
-
- if (timespan.fromDates(this._context.from, this._context.until) < 0
- || this._context.until === this._context.from) { |
If the length of the timespan for this Search instance is -negative then set it to default values | this._context.until = 'NOW';
- this._context.from = 'NOW-24HOURS';
- }
-
- return this;
-};
-
- |
- npm install request -- -Or from source: - -
- git clone git://github.com/mikeal/request.git - cd request - npm link -- -## Super simple to use - -Request is designed to be the simplest way possible to make http calls. It support HTTPS and follows redirects by default. - -```javascript -var request = require('request'); -request('http://www.google.com', function (error, response, body) { - if (!error && response.statusCode == 200) { - console.log(body) // Print the google web page. - } -}) -``` - -## Streaming - -You can stream any response to a file stream. - -```javascript -request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')) -``` - -You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types, in this case `application/json`, and use the proper content-type in the PUT request if one is not already provided in the headers. - -```javascript -fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json')) -``` - -Request can also pipe to itself. When doing so the content-type and content-length will be preserved in the PUT headers. - -```javascript -request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png')) -``` - -Now let's get fancy. - -```javascript -http.createServer(function (req, resp) { - if (req.url === '/doodle.png') { - if (req.method === 'PUT') { - req.pipe(request.put('http://mysite.com/doodle.png')) - } else if (req.method === 'GET' || req.method === 'HEAD') { - request.get('http://mysite.com/doodle.png').pipe(resp) - } - } -}) -``` - -You can also pipe() from a http.ServerRequest instance and to a http.ServerResponse instance. The HTTP method and headers will be sent as well as the entity-body data. Which means that, if you don't really care about security, you can do: - -```javascript -http.createServer(function (req, resp) { - if (req.url === '/doodle.png') { - var x = request('http://mysite.com/doodle.png') - req.pipe(x) - x.pipe(resp) - } -}) -``` - -And since pipe() returns the destination stream in node 0.5.x you can do one line proxying :) - -```javascript -req.pipe(request('http://mysite.com/doodle.png')).pipe(resp) -``` - -Also, none of this new functionality conflicts with requests previous features, it just expands them. - -```javascript -var r = request.defaults({'proxy':'http://localproxy.com'}) - -http.createServer(function (req, resp) { - if (req.url === '/doodle.png') { - r.get('http://google.com/doodle.png').pipe(resp) - } -}) -``` - -You can still use intermediate proxies, the requests will still follow HTTP forwards, etc. - -## OAuth Signing - -```javascript -// Twitter OAuth -var qs = require('querystring') - , oauth = - { callback: 'http://mysite.com/callback/' - , consumer_key: CONSUMER_KEY - , consumer_secret: CONSUMER_SECRET - } - , url = 'https://api.twitter.com/oauth/request_token' - ; -request.post({url:url, oauth:oauth}, function (e, r, body) { - // Assume by some stretch of magic you aquired the verifier - var access_token = qs.parse(body) - , oauth = - { consumer_key: CONSUMER_KEY - , consumer_secret: CONSUMER_SECRET - , token: access_token.oauth_token - , verifier: VERIFIER - , token_secret: access_token.oauth_token_secret - } - , url = 'https://api.twitter.com/oauth/access_token' - ; - request.post({url:url, oauth:oauth}, function (e, r, body) { - var perm_token = qs.parse(body) - , oauth = - { consumer_key: CONSUMER_KEY - , consumer_secret: CONSUMER_SECRET - , token: perm_token.oauth_token - , token_secret: perm_token.oauth_token_secret - } - , url = 'https://api.twitter.com/1/users/show.json?' - , params = - { screen_name: perm_token.screen_name - , user_id: perm_token.user_id - } - ; - url += qs.stringify(params) - request.get({url:url, oauth:oauth, json:true}, function (e, r, user) { - console.log(user) - }) - }) -}) -``` - - - -### request(options, callback) - -The first argument can be either a url or an options object. The only required option is uri, all others are optional. - -* `uri` || `url` - fully qualified uri or a parsed url object from url.parse() -* `qs` - object containing querystring values to be appended to the uri -* `method` - http method, defaults to GET -* `headers` - http headers, defaults to {} -* `body` - entity body for POST and PUT requests. Must be buffer or string. -* `form` - sets `body` but to querystring representation of value and adds `Content-type: application/x-www-form-urlencoded; charset=utf-8` header. -* `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header. -* `multipart` - (experimental) array of objects which contains their own headers and `body` attribute. Sends `multipart/related` request. See example below. -* `followRedirect` - follow HTTP 3xx responses as redirects. defaults to true. -* `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects. defaults to false. -* `maxRedirects` - the maximum number of redirects to follow, defaults to 10. -* `onResponse` - If true the callback will be fired on the "response" event instead of "end". If a function it will be called on "response" and not effect the regular semantics of the main callback on "end". -* `encoding` - Encoding to be used on `setEncoding` of response data. If set to `null`, the body is returned as a Buffer. -* `pool` - A hash object containing the agents for these requests. If omitted this request will use the global pool which is set to node's default maxSockets. -* `pool.maxSockets` - Integer containing the maximum amount of sockets in the pool. -* `timeout` - Integer containing the number of milliseconds to wait for a request to respond before aborting the request -* `proxy` - An HTTP proxy to be used. Support proxy Auth with Basic Auth the same way it's supported with the `url` parameter by embedding the auth info in the uri. -* `oauth` - Options for OAuth HMAC-SHA1 signing, see documentation above. -* `strictSSL` - Set to `true` to require that SSL certificates be valid. Note: to use your own certificate authority, you need to specify an agent that was created with that ca as an option. -* `jar` - Set to `false` if you don't want cookies to be remembered for future use or define your custom cookie jar (see examples section) - - -The callback argument gets 3 arguments. The first is an error when applicable (usually from the http.Client option not the http.ClientRequest object). The second in an http.ClientResponse object. The third is the response body String or Buffer. - -## Convenience methods - -There are also shorthand methods for different HTTP METHODs and some other conveniences. - -### request.defaults(options) - -This method returns a wrapper around the normal request API that defaults to whatever options you pass in to it. - -### request.put - -Same as request() but defaults to `method: "PUT"`. - -```javascript -request.put(url) -``` - -### request.post - -Same as request() but defaults to `method: "POST"`. - -```javascript -request.post(url) -``` - -### request.head - -Same as request() but defaults to `method: "HEAD"`. - -```javascript -request.head(url) -``` - -### request.del - -Same as request() but defaults to `method: "DELETE"`. - -```javascript -request.del(url) -``` - -### request.get - -Alias to normal request method for uniformity. - -```javascript -request.get(url) -``` -### request.cookie - -Function that creates a new cookie. - -```javascript -request.cookie('cookie_string_here') -``` -### request.jar - -Function that creates a new cookie jar. - -```javascript -request.jar() -``` - - -## Examples: - -```javascript - var request = require('request') - , rand = Math.floor(Math.random()*100000000).toString() - ; - request( - { method: 'PUT' - , uri: 'http://mikeal.iriscouch.com/testjs/' + rand - , multipart: - [ { 'content-type': 'application/json' - , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) - } - , { body: 'I am an attachment' } - ] - } - , function (error, response, body) { - if(response.statusCode == 201){ - console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand) - } else { - console.log('error: '+ response.statusCode) - console.log(body) - } - } - ) -``` -Cookies are enabled by default (so they can be used in subsequent requests). To disable cookies set jar to false (either in defaults or in the options sent). - -```javascript -var request = request.defaults({jar: false}) -request('http://www.google.com', function () { - request('http://images.google.com') -}) -``` - -If you to use a custom cookie jar (instead of letting request use its own global cookie jar) you do so by setting the jar default or by specifying it as an option: - -```javascript -var j = request.jar() -var request = request.defaults({jar:j}) -request('http://www.google.com', function () { - request('http://images.google.com') -}) -``` -OR - -```javascript -var j = request.jar() -var cookie = request.cookie('your_cookie_here') -j.add(cookie) -request({url: 'http://www.google.com', jar: j}, function () { - request('http://images.google.com') -}) -``` diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/forever.js b/node_modules/winston/node_modules/loggly/node_modules/request/forever.js deleted file mode 100644 index e6531a2..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/forever.js +++ /dev/null @@ -1,84 +0,0 @@ -module.exports = ForeverAgent - -var util = require('util') - , Agent = require('http').Agent - , net = require('net') - -function ForeverAgent(options) { - var self = this - self.options = options || {} - self.requests = {} - self.sockets = {} - self.freeSockets = {} - self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets - self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets - self.on('free', function(socket, host, port) { - var name = host + ':' + port - if (self.requests[name] && self.requests[name].length) { - self.requests[name].shift().onSocket(socket) - } else if (self.sockets[name].length < self.minSockets) { - if (!self.freeSockets[name]) self.freeSockets[name] = [] - self.freeSockets[name].push(socket) - - // if an error happens while we don't use the socket anyway, meh, throw the socket away - function onIdleError() { - socket.destroy() - } - socket._onIdleError = onIdleError - socket.on('error', onIdleError) - } else { - // If there are no pending requests just destroy the - // socket and it will get removed from the pool. This - // gets us out of timeout issues and allows us to - // default to Connection:keep-alive. - socket.destroy(); - } - }) - self.createConnection = net.createConnection -} -util.inherits(ForeverAgent, Agent) - -ForeverAgent.defaultMinSockets = 5 - -ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest -ForeverAgent.prototype.addRequest = function(req, host, port) { - var name = host + ':' + port - if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) { - var idleSocket = this.freeSockets[name].pop() - idleSocket.removeListener('error', idleSocket._onIdleError) - delete idleSocket._onIdleError - req._reusedSocket = true - req.onSocket(idleSocket) - } else { - this.addRequestNoreuse(req, host, port) - } -} - -ForeverAgent.prototype.removeSocket = function(s, name, host, port) { - if (this.sockets[name]) { - var index = this.sockets[name].indexOf(s); - if (index !== -1) { - this.sockets[name].splice(index, 1); - } - } else if (this.sockets[name] && this.sockets[name].length === 0) { - // don't leak - delete this.sockets[name]; - delete this.requests[name]; - } - - if (this.freeSockets[name]) { - var index = this.freeSockets[name].indexOf(s) - if (index !== -1) { - this.freeSockets[name].splice(index, 1) - if (this.freeSockets[name].length === 0) { - delete this.freeSockets[name] - } - } - } - - if (this.requests[name] && this.requests[name].length) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(name, host, port).emit('free'); - } -} diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/main.js b/node_modules/winston/node_modules/loggly/node_modules/request/main.js deleted file mode 100644 index 6530598..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/main.js +++ /dev/null @@ -1,804 +0,0 @@ -// Copyright 2010-2012 Mikeal Rogers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -var http = require('http') - , https = false - , tls = false - , url = require('url') - , util = require('util') - , stream = require('stream') - , qs = require('querystring') - , mimetypes = require('./mimetypes') - , oauth = require('./oauth') - , uuid = require('./uuid') - , ForeverAgent = require('./forever') - , Cookie = require('./vendor/cookie') - , CookieJar = require('./vendor/cookie/jar') - , cookieJar = new CookieJar - ; - -if (process.logging) { - var log = process.logging('request') -} - -try { - https = require('https') -} catch (e) {} - -try { - tls = require('tls') -} catch (e) {} - -function toBase64 (str) { - return (new Buffer(str || "", "ascii")).toString("base64") -} - -// Hacky fix for pre-0.4.4 https -if (https && !https.Agent) { - https.Agent = function (options) { - http.Agent.call(this, options) - } - util.inherits(https.Agent, http.Agent) - https.Agent.prototype._getConnection = function(host, port, cb) { - var s = tls.connect(port, host, this.options, function() { - // do other checks here? - if (cb) cb() - }) - return s - } -} - -function isReadStream (rs) { - if (rs.readable && rs.path && rs.mode) { - return true - } -} - -function copy (obj) { - var o = {} - Object.keys(obj).forEach(function (i) { - o[i] = obj[i] - }) - return o -} - -var isUrl = /^https?:/ - -var globalPool = {} - -function Request (options) { - stream.Stream.call(this) - this.readable = true - this.writable = true - - if (typeof options === 'string') { - options = {uri:options} - } - - var reserved = Object.keys(Request.prototype) - for (var i in options) { - if (reserved.indexOf(i) === -1) { - this[i] = options[i] - } else { - if (typeof options[i] === 'function') { - delete options[i] - } - } - } - options = copy(options) - - this.init(options) -} -util.inherits(Request, stream.Stream) -Request.prototype.init = function (options) { - var self = this - - if (!options) options = {} - - if (!self.pool) self.pool = globalPool - self.dests = [] - self.__isRequestRequest = true - - // Protect against double callback - if (!self._callback && self.callback) { - self._callback = self.callback - self.callback = function () { - if (self._callbackCalled) return // Print a warning maybe? - self._callback.apply(self, arguments) - self._callbackCalled = true - } - } - - if (self.url) { - // People use this property instead all the time so why not just support it. - self.uri = self.url - delete self.url - } - - if (!self.uri) { - throw new Error("options.uri is a required argument") - } else { - if (typeof self.uri == "string") self.uri = url.parse(self.uri) - } - if (self.proxy) { - if (typeof self.proxy == 'string') self.proxy = url.parse(self.proxy) - } - - self._redirectsFollowed = self._redirectsFollowed || 0 - self.maxRedirects = (self.maxRedirects !== undefined) ? self.maxRedirects : 10 - self.followRedirect = (self.followRedirect !== undefined) ? self.followRedirect : true - self.followAllRedirects = (self.followAllRedirects !== undefined) ? self.followAllRedirects : false; - if (self.followRedirect || self.followAllRedirects) - self.redirects = self.redirects || [] - - self.headers = self.headers ? copy(self.headers) : {} - - self.setHost = false - if (!self.headers.host) { - self.headers.host = self.uri.hostname - if (self.uri.port) { - if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') && - !(self.uri.port === 443 && self.uri.protocol === 'https:') ) - self.headers.host += (':'+self.uri.port) - } - self.setHost = true - } - - self.jar(options.jar) - - if (!self.uri.pathname) {self.uri.pathname = '/'} - if (!self.uri.port) { - if (self.uri.protocol == 'http:') {self.uri.port = 80} - else if (self.uri.protocol == 'https:') {self.uri.port = 443} - } - - if (self.proxy) { - self.port = self.proxy.port - self.host = self.proxy.hostname - } else { - self.port = self.uri.port - self.host = self.uri.hostname - } - - if (self.onResponse === true) { - self.onResponse = self.callback - delete self.callback - } - - self.clientErrorHandler = function (error) { - if (self._aborted) return - - if (self.setHost) delete self.headers.host - if (self.req._reusedSocket && error.code === 'ECONNRESET') { - self.agent = {addRequest: ForeverAgent.prototype.addRequestNoreuse.bind(self.agent)} - self.start() - self.req.end() - return - } - if (self.timeout && self.timeoutTimer) { - clearTimeout(self.timeoutTimer); - self.timeoutTimer = null; - } - self.emit('error', error) - } - if (self.onResponse) self.on('error', function (e) {self.onResponse(e)}) - if (self.callback) self.on('error', function (e) {self.callback(e)}) - - if (options.form) { - self.form(options.form) - } - - if (options.oauth) { - self.oauth(options.oauth) - } - - if (self.uri.auth && !self.headers.authorization) { - self.headers.authorization = "Basic " + toBase64(self.uri.auth.split(':').map(function(item){ return qs.unescape(item)}).join(':')) - } - if (self.proxy && self.proxy.auth && !self.headers['proxy-authorization']) { - self.headers['proxy-authorization'] = "Basic " + toBase64(self.proxy.auth.split(':').map(function(item){ return qs.unescape(item)}).join(':')) - } - - if (options.qs) self.qs(options.qs) - - if (self.uri.path) { - self.path = self.uri.path - } else { - self.path = self.uri.pathname + (self.uri.search || "") - } - - if (self.path.length === 0) self.path = '/' - - if (self.proxy) self.path = (self.uri.protocol + '//' + self.uri.host + self.path) - - if (options.json) { - self.json(options.json) - } else if (options.multipart) { - self.multipart(options.multipart) - } - - if (self.body) { - var length = 0 - if (!Buffer.isBuffer(self.body)) { - if (Array.isArray(self.body)) { - for (var i = 0; i < self.body.length; i++) { - length += self.body[i].length - } - } else { - self.body = new Buffer(self.body) - length = self.body.length - } - } else { - length = self.body.length - } - if (length) { - self.headers['content-length'] = length - } else { - throw new Error('Argument error, options.body.') - } - } - - var protocol = self.proxy ? self.proxy.protocol : self.uri.protocol - , defaultModules = {'http:':http, 'https:':https} - , httpModules = self.httpModules || {} - ; - self.httpModule = httpModules[protocol] || defaultModules[protocol] - - if (!self.httpModule) throw new Error("Invalid protocol") - - if (self.pool === false) { - self.agent = false - } else { - if (self.maxSockets) { - // Don't use our pooling if node has the refactored client - self.agent = self.agent || self.httpModule.globalAgent || self.getAgent(self.host, self.port) - self.agent.maxSockets = self.maxSockets - } - if (self.pool.maxSockets) { - // Don't use our pooling if node has the refactored client - self.agent = self.agent || self.httpModule.globalAgent || self.getAgent(self.host, self.port) - self.agent.maxSockets = self.pool.maxSockets - } - } - - self.once('pipe', function (src) { - if (self.ntick) throw new Error("You cannot pipe to this stream after the first nextTick() after creation of the request stream.") - self.src = src - if (isReadStream(src)) { - if (!self.headers['content-type'] && !self.headers['Content-Type']) - self.headers['content-type'] = mimetypes.lookup(src.path.slice(src.path.lastIndexOf('.')+1)) - } else { - if (src.headers) { - for (var i in src.headers) { - if (!self.headers[i]) { - self.headers[i] = src.headers[i] - } - } - } - if (src.method && !self.method) { - self.method = src.method - } - } - - self.on('pipe', function () { - console.error("You have already piped to this stream. Pipeing twice is likely to break the request.") - }) - }) - - process.nextTick(function () { - if (self._aborted) return - - if (self.body) { - if (Array.isArray(self.body)) { - self.body.forEach(function(part) { - self.write(part) - }) - } else { - self.write(self.body) - } - self.end() - } else if (self.requestBodyStream) { - console.warn("options.requestBodyStream is deprecated, please pass the request object to stream.pipe.") - self.requestBodyStream.pipe(self) - } else if (!self.src) { - self.headers['content-length'] = 0 - self.end() - } - self.ntick = true - }) -} -Request.prototype.getAgent = function (host, port) { - if (!this.pool[host+':'+port]) { - this.pool[host+':'+port] = new this.httpModule.Agent({host:host, port:port}) - } - return this.pool[host+':'+port] -} -Request.prototype.start = function () { - var self = this - - if (self._aborted) return - - self._started = true - self.method = self.method || 'GET' - self.href = self.uri.href - if (log) log('%method %href', self) - self.req = self.httpModule.request(self, function (response) { - if (self._aborted) return - - self.response = response - response.request = self - - if (self.httpModule === https && - self.strictSSL && - !response.client.authorized) { - var sslErr = response.client.authorizationError - self.emit('error', new Error('SSL Error: '+ sslErr)) - return - } - - if (self.setHost) delete self.headers.host - if (self.timeout && self.timeoutTimer) { - clearTimeout(self.timeoutTimer); - self.timeoutTimer = null; - } - - if (response.headers['set-cookie'] && (!self._disableCookies)) { - response.headers['set-cookie'].forEach(function(cookie) { - if (self._jar) self._jar.add(new Cookie(cookie)) - else cookieJar.add(new Cookie(cookie)) - }) - } - - if (response.statusCode >= 300 && response.statusCode < 400 && - (self.followAllRedirects || - (self.followRedirect && (self.method !== 'PUT' && self.method !== 'POST'))) && - response.headers.location) { - if (self._redirectsFollowed >= self.maxRedirects) { - self.emit('error', new Error("Exceeded maxRedirects. Probably stuck in a redirect loop.")) - return - } - self._redirectsFollowed += 1 - - if (!isUrl.test(response.headers.location)) { - response.headers.location = url.resolve(self.uri.href, response.headers.location) - } - self.uri = response.headers.location - self.redirects.push( - { statusCode : response.statusCode - , redirectUri: response.headers.location - } - ) - self.method = 'GET'; // Force all redirects to use GET - delete self.req - delete self.agent - delete self._started - if (self.headers) { - delete self.headers.host - } - if (log) log('Redirect to %uri', self) - self.init() - return // Ignore the rest of the response - } else { - self._redirectsFollowed = self._redirectsFollowed || 0 - // Be a good stream and emit end when the response is finished. - // Hack to emit end on close because of a core bug that never fires end - response.on('close', function () { - if (!self._ended) self.response.emit('end') - }) - - if (self.encoding) { - if (self.dests.length !== 0) { - console.error("Ingoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.") - } else { - response.setEncoding(self.encoding) - } - } - - self.dests.forEach(function (dest) { - self.pipeDest(dest) - }) - - response.on("data", function (chunk) { - self._destdata = true - self.emit("data", chunk) - }) - response.on("end", function (chunk) { - self._ended = true - self.emit("end", chunk) - }) - response.on("close", function () {self.emit("close")}) - - self.emit('response', response) - - if (self.onResponse) { - self.onResponse(null, response) - } - if (self.callback) { - var buffer = [] - var bodyLen = 0 - self.on("data", function (chunk) { - buffer.push(chunk) - bodyLen += chunk.length - }) - self.on("end", function () { - if (self._aborted) return - - if (buffer.length && Buffer.isBuffer(buffer[0])) { - var body = new Buffer(bodyLen) - var i = 0 - buffer.forEach(function (chunk) { - chunk.copy(body, i, 0, chunk.length) - i += chunk.length - }) - if (self.encoding === null) { - response.body = body - } else { - response.body = body.toString() - } - } else if (buffer.length) { - response.body = buffer.join('') - } - - if (self._json) { - try { - response.body = JSON.parse(response.body) - } catch (e) {} - } - - self.callback(null, response, response.body) - }) - } - } - }) - - if (self.timeout && !self.timeoutTimer) { - self.timeoutTimer = setTimeout(function() { - self.req.abort() - var e = new Error("ETIMEDOUT") - e.code = "ETIMEDOUT" - self.emit("error", e) - }, self.timeout) - - // Set additional timeout on socket - in case if remote - // server freeze after sending headers - self.req.setTimeout(self.timeout, function(){ - if (self.req) { - self.req.abort() - var e = new Error("ESOCKETTIMEDOUT") - e.code = "ESOCKETTIMEDOUT" - self.emit("error", e) - } - }); - } - - self.req.on('error', self.clientErrorHandler) - - self.emit('request', self.req) -} - -Request.prototype.abort = function() { - this._aborted = true; - - if (this.req) { - this.req.abort() - } - else if (this.response) { - this.response.abort() - } - - this.emit("abort") -} - -Request.prototype.pipeDest = function (dest) { - var response = this.response - // Called after the response is received - if (dest.headers) { - dest.headers['content-type'] = response.headers['content-type'] - if (response.headers['content-length']) { - dest.headers['content-length'] = response.headers['content-length'] - } - } - if (dest.setHeader) { - for (var i in response.headers) { - dest.setHeader(i, response.headers[i]) - } - dest.statusCode = response.statusCode - } - if (this.pipefilter) this.pipefilter(response, dest) -} - -// Composable API -Request.prototype.setHeader = function (name, value, clobber) { - if (clobber === undefined) clobber = true - if (clobber || !this.headers.hasOwnProperty(name)) this.headers[name] = value - else this.headers[name] += ',' + value - return this -} -Request.prototype.setHeaders = function (headers) { - for (i in headers) {this.setHeader(i, headers[i])} - return this -} -Request.prototype.qs = function (q, clobber) { - var uri = { - protocol: this.uri.protocol, - host: this.uri.host, - pathname: this.uri.pathname, - query: clobber ? q : qs.parse(this.uri.query), - hash: this.uri.hash - }; - if (!clobber) for (var i in q) uri.query[i] = q[i] - - this.uri= url.parse(url.format(uri)) - - return this -} -Request.prototype.form = function (form) { - this.headers['content-type'] = 'application/x-www-form-urlencoded; charset=utf-8' - this.body = qs.stringify(form).toString('utf8') - return this -} -Request.prototype.multipart = function (multipart) { - var self = this - self.body = [] - - if (!self.headers['content-type']) { - self.headers['content-type'] = 'multipart/related;boundary="frontier"'; - } else { - self.headers['content-type'] = self.headers['content-type'].split(';')[0] + ';boundary="frontier"'; - } - - if (!multipart.forEach) throw new Error('Argument error, options.multipart.') - - multipart.forEach(function (part) { - var body = part.body - if(!body) throw Error('Body attribute missing in multipart.') - delete part.body - var preamble = '--frontier\r\n' - Object.keys(part).forEach(function(key){ - preamble += key + ': ' + part[key] + '\r\n' - }) - preamble += '\r\n' - self.body.push(new Buffer(preamble)) - self.body.push(new Buffer(body)) - self.body.push(new Buffer('\r\n')) - }) - self.body.push(new Buffer('--frontier--')) - return self -} -Request.prototype.json = function (val) { - this.setHeader('content-type', 'application/json') - this.setHeader('accept', 'application/json') - this._json = true - if (typeof val === 'boolean') { - if (typeof this.body === 'object') this.body = JSON.stringify(this.body) - } else { - this.body = JSON.stringify(val) - } - return this -} -Request.prototype.oauth = function (_oauth) { - var form - if (this.headers['content-type'] && - this.headers['content-type'].slice(0, 'application/x-www-form-urlencoded'.length) === - 'application/x-www-form-urlencoded' - ) { - form = qs.parse(this.body) - } - if (this.uri.query) { - form = qs.parse(this.uri.query) - } - if (!form) form = {} - var oa = {} - for (var i in form) oa[i] = form[i] - for (var i in _oauth) oa['oauth_'+i] = _oauth[i] - if (!oa.oauth_version) oa.oauth_version = '1.0' - if (!oa.oauth_timestamp) oa.oauth_timestamp = Math.floor( (new Date()).getTime() / 1000 ).toString() - if (!oa.oauth_nonce) oa.oauth_nonce = uuid().replace(/-/g, '') - - oa.oauth_signature_method = 'HMAC-SHA1' - - var consumer_secret = oa.oauth_consumer_secret - delete oa.oauth_consumer_secret - var token_secret = oa.oauth_token_secret - delete oa.oauth_token_secret - - var baseurl = this.uri.protocol + '//' + this.uri.host + this.uri.pathname - var signature = oauth.hmacsign(this.method, baseurl, oa, consumer_secret, token_secret) - - // oa.oauth_signature = signature - for (var i in form) { - if ( i.slice(0, 'oauth_') in _oauth) { - // skip - } else { - delete oa['oauth_'+i] - } - } - this.headers.authorization = - 'OAuth '+Object.keys(oa).sort().map(function (i) {return i+'="'+oauth.rfc3986(oa[i])+'"'}).join(',') - this.headers.authorization += ',oauth_signature="'+oauth.rfc3986(signature)+'"' - return this -} -Request.prototype.jar = function (jar) { - var cookies - - if (this._redirectsFollowed === 0) { - this.originalCookieHeader = this.headers.cookie - } - - if (jar === false) { - // disable cookies - cookies = false; - this._disableCookies = true; - } else if (jar) { - // fetch cookie from the user defined cookie jar - cookies = jar.get({ url: this.uri.href }) - } else { - // fetch cookie from the global cookie jar - cookies = cookieJar.get({ url: this.uri.href }) - } - - if (cookies && cookies.length) { - var cookieString = cookies.map(function (c) { - return c.name + "=" + c.value - }).join("; ") - - if (this.originalCookieHeader) { - // Don't overwrite existing Cookie header - this.headers.cookie = this.originalCookieHeader + '; ' + cookieString - } else { - this.headers.cookie = cookieString - } - } - this._jar = jar - return this -} - - -// Stream API -Request.prototype.pipe = function (dest, opts) { - if (this.response) { - if (this._destdata) { - throw new Error("You cannot pipe after data has been emitted from the response.") - } else if (this._ended) { - throw new Error("You cannot pipe after the response has been ended.") - } else { - stream.Stream.prototype.pipe.call(this, dest, opts) - this.pipeDest(dest) - return dest - } - } else { - this.dests.push(dest) - stream.Stream.prototype.pipe.call(this, dest, opts) - return dest - } -} -Request.prototype.write = function () { - if (!this._started) this.start() - if (!this.req) throw new Error("This request has been piped before http.request() was called.") - this.req.write.apply(this.req, arguments) -} -Request.prototype.end = function (chunk) { - if (chunk) this.write(chunk) - if (!this._started) this.start() - if (!this.req) throw new Error("This request has been piped before http.request() was called.") - this.req.end() -} -Request.prototype.pause = function () { - if (!this.response) throw new Error("This request has been piped before http.request() was called.") - this.response.pause.apply(this.response, arguments) -} -Request.prototype.resume = function () { - if (!this.response) throw new Error("This request has been piped before http.request() was called.") - this.response.resume.apply(this.response, arguments) -} -Request.prototype.destroy = function () { - if (!this._ended) this.end() -} - -// organize params for post, put, head, del -function initParams(uri, options, callback) { - if ((typeof options === 'function') && !callback) callback = options; - if (typeof options === 'object') { - options.uri = uri; - } else if (typeof uri === 'string') { - options = {uri:uri}; - } else { - options = uri; - uri = options.uri; - } - return { uri: uri, options: options, callback: callback }; -} - -function request (uri, options, callback) { - if ((typeof options === 'function') && !callback) callback = options; - if (typeof options === 'object') { - options.uri = uri; - } else if (typeof uri === 'string') { - options = {uri:uri}; - } else { - options = uri; - } - - if (callback) options.callback = callback; - var r = new Request(options) - return r -} - -module.exports = request - -request.defaults = function (options) { - var def = function (method) { - var d = function (uri, opts, callback) { - var params = initParams(uri, opts, callback); - for (var i in options) { - if (params.options[i] === undefined) params.options[i] = options[i] - } - return method(params.uri, params.options, params.callback) - } - return d - } - var de = def(request) - de.get = def(request.get) - de.post = def(request.post) - de.put = def(request.put) - de.head = def(request.head) - de.del = def(request.del) - de.cookie = def(request.cookie) - de.jar = def(request.jar) - return de -} - -request.forever = function (agentOptions, optionsArg) { - var options = {} - if (agentOptions) { - for (option in optionsArg) { - options[option] = optionsArg[option] - } - } - options.agent = new ForeverAgent(agentOptions) - return request.defaults(options) -} - -request.get = request -request.post = function (uri, options, callback) { - var params = initParams(uri, options, callback); - params.options.method = 'POST'; - return request(params.uri, params.options, params.callback) -} -request.put = function (uri, options, callback) { - var params = initParams(uri, options, callback); - params.options.method = 'PUT' - return request(params.uri, params.options, params.callback) -} -request.head = function (uri, options, callback) { - var params = initParams(uri, options, callback); - params.options.method = 'HEAD' - if (params.options.body || params.options.requestBodyStream || params.options.json || params.options.multipart) { - throw new Error("HTTP HEAD requests MUST NOT include a request body.") - } - return request(params.uri, params.options, params.callback) -} -request.del = function (uri, options, callback) { - var params = initParams(uri, options, callback); - params.options.method = 'DELETE' - return request(params.uri, params.options, params.callback) -} -request.jar = function () { - return new CookieJar -} -request.cookie = function (str) { - if (str && str.uri) str = str.uri - if (typeof str !== 'string') throw new Error("The cookie function only accepts STRING as param") - return new Cookie(str) -} diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/mimetypes.js b/node_modules/winston/node_modules/loggly/node_modules/request/mimetypes.js deleted file mode 100644 index 59b21b4..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/mimetypes.js +++ /dev/null @@ -1,152 +0,0 @@ -// from http://github.com/felixge/node-paperboy -exports.types = { - "3gp":"video/3gpp", - "aiff":"audio/x-aiff", - "arj":"application/x-arj-compressed", - "asf":"video/x-ms-asf", - "asx":"video/x-ms-asx", - "au":"audio/ulaw", - "avi":"video/x-msvideo", - "bcpio":"application/x-bcpio", - "ccad":"application/clariscad", - "cod":"application/vnd.rim.cod", - "com":"application/x-msdos-program", - "cpio":"application/x-cpio", - "cpt":"application/mac-compactpro", - "csh":"application/x-csh", - "css":"text/css", - "deb":"application/x-debian-package", - "dl":"video/dl", - "doc":"application/msword", - "drw":"application/drafting", - "dvi":"application/x-dvi", - "dwg":"application/acad", - "dxf":"application/dxf", - "dxr":"application/x-director", - "etx":"text/x-setext", - "ez":"application/andrew-inset", - "fli":"video/x-fli", - "flv":"video/x-flv", - "gif":"image/gif", - "gl":"video/gl", - "gtar":"application/x-gtar", - "gz":"application/x-gzip", - "hdf":"application/x-hdf", - "hqx":"application/mac-binhex40", - "html":"text/html", - "ice":"x-conference/x-cooltalk", - "ico":"image/x-icon", - "ief":"image/ief", - "igs":"model/iges", - "ips":"application/x-ipscript", - "ipx":"application/x-ipix", - "jad":"text/vnd.sun.j2me.app-descriptor", - "jar":"application/java-archive", - "jpeg":"image/jpeg", - "jpg":"image/jpeg", - "js":"text/javascript", - "json":"application/json", - "latex":"application/x-latex", - "lsp":"application/x-lisp", - "lzh":"application/octet-stream", - "m":"text/plain", - "m3u":"audio/x-mpegurl", - "m4v":"video/mp4", - "man":"application/x-troff-man", - "me":"application/x-troff-me", - "midi":"audio/midi", - "mif":"application/x-mif", - "mime":"www/mime", - "mkv":" video/x-matrosk", - "movie":"video/x-sgi-movie", - "mp4":"video/mp4", - "mp41":"video/mp4", - "mp42":"video/mp4", - "mpg":"video/mpeg", - "mpga":"audio/mpeg", - "ms":"application/x-troff-ms", - "mustache":"text/plain", - "nc":"application/x-netcdf", - "oda":"application/oda", - "ogm":"application/ogg", - "pbm":"image/x-portable-bitmap", - "pdf":"application/pdf", - "pgm":"image/x-portable-graymap", - "pgn":"application/x-chess-pgn", - "pgp":"application/pgp", - "pm":"application/x-perl", - "png":"image/png", - "pnm":"image/x-portable-anymap", - "ppm":"image/x-portable-pixmap", - "ppz":"application/vnd.ms-powerpoint", - "pre":"application/x-freelance", - "prt":"application/pro_eng", - "ps":"application/postscript", - "qt":"video/quicktime", - "ra":"audio/x-realaudio", - "rar":"application/x-rar-compressed", - "ras":"image/x-cmu-raster", - "rgb":"image/x-rgb", - "rm":"audio/x-pn-realaudio", - "rpm":"audio/x-pn-realaudio-plugin", - "rtf":"text/rtf", - "rtx":"text/richtext", - "scm":"application/x-lotusscreencam", - "set":"application/set", - "sgml":"text/sgml", - "sh":"application/x-sh", - "shar":"application/x-shar", - "silo":"model/mesh", - "sit":"application/x-stuffit", - "skt":"application/x-koan", - "smil":"application/smil", - "snd":"audio/basic", - "sol":"application/solids", - "spl":"application/x-futuresplash", - "src":"application/x-wais-source", - "stl":"application/SLA", - "stp":"application/STEP", - "sv4cpio":"application/x-sv4cpio", - "sv4crc":"application/x-sv4crc", - "svg":"image/svg+xml", - "swf":"application/x-shockwave-flash", - "tar":"application/x-tar", - "tcl":"application/x-tcl", - "tex":"application/x-tex", - "texinfo":"application/x-texinfo", - "tgz":"application/x-tar-gz", - "tiff":"image/tiff", - "tr":"application/x-troff", - "tsi":"audio/TSP-audio", - "tsp":"application/dsptype", - "tsv":"text/tab-separated-values", - "unv":"application/i-deas", - "ustar":"application/x-ustar", - "vcd":"application/x-cdlink", - "vda":"application/vda", - "vivo":"video/vnd.vivo", - "vrm":"x-world/x-vrml", - "wav":"audio/x-wav", - "wax":"audio/x-ms-wax", - "webm":"video/webm", - "wma":"audio/x-ms-wma", - "wmv":"video/x-ms-wmv", - "wmx":"video/x-ms-wmx", - "wrl":"model/vrml", - "wvx":"video/x-ms-wvx", - "xbm":"image/x-xbitmap", - "xlw":"application/vnd.ms-excel", - "xml":"text/xml", - "xpm":"image/x-xpixmap", - "xwd":"image/x-xwindowdump", - "xyz":"chemical/x-pdb", - "zip":"application/zip" -}; - -exports.lookup = function(ext, defaultType) { - defaultType = defaultType || 'application/octet-stream'; - - return (ext in exports.types) - ? exports.types[ext] - : defaultType; -}; \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/oauth.js b/node_modules/winston/node_modules/loggly/node_modules/request/oauth.js deleted file mode 100644 index 31b9dc6..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/oauth.js +++ /dev/null @@ -1,34 +0,0 @@ -var crypto = require('crypto') - , qs = require('querystring') - ; - -function sha1 (key, body) { - return crypto.createHmac('sha1', key).update(body).digest('base64') -} - -function rfc3986 (str) { - return encodeURIComponent(str) - .replace('!','%21') - .replace('*','%2A') - .replace('(','%28') - .replace(')','%29') - .replace("'",'%27') - ; -} - -function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret, body) { - // adapted from https://dev.twitter.com/docs/auth/oauth - var base = - (httpMethod || 'GET') + "&" + - encodeURIComponent( base_uri ) + "&" + - Object.keys(params).sort().map(function (i) { - // big WTF here with the escape + encoding but it's what twitter wants - return escape(rfc3986(i)) + "%3D" + escape(rfc3986(params[i])) - }).join("%26") - var key = consumer_secret + '&' - if (token_secret) key += token_secret - return sha1(key, base) -} - -exports.hmacsign = hmacsign -exports.rfc3986 = rfc3986 \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/package.json b/node_modules/winston/node_modules/loggly/node_modules/request/package.json deleted file mode 100644 index 71eca50..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ "name" : "request" -, "description" : "Simplified HTTP request client." -, "tags" : ["http", "simple", "util", "utility"] -, "version" : "2.9.152" -, "author" : "Mikeal Rogers
time-span.js | |
---|---|
/*
-* JavaScript TimeSpan Library
-*
-* Copyright (c) 2010 Michael Stum, Charlie Robbins
-*
-* 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.
-*/ | |
Time constants | var msecPerSecond = 1000,
- msecPerMinute = 60000,
- msecPerHour = 3600000,
- msecPerDay = 86400000; |
Timespan Parsers | var timeSpanWithDays = /^(\d+):(\d+):(\d+):(\d+)(\.\d+)?/,
- timeSpanNoDays = /^(\d+):(\d+):(\d+)(\.\d+)?/; |
function TimeSpan (milliseconds, seconds, minutes, hours, days)- -@milliseconds {Number} Number of milliseconds for this instance.- -@seconds {Number} Number of seconds for this instance.- -@minutes {Number} Number of minutes for this instance.- -@hours {Number} Number of hours for this instance.- -@days {Number} Number of days for this instance.- -Constructor function for the | var TimeSpan = exports.TimeSpan = function (milliseconds, seconds, minutes, hours, days) {
- this.msecs = 0;
-
- if (isNumeric(days)) {
- this.msecs += (days * msecPerDay);
- }
-
- if (isNumeric(hours)) {
- this.msecs += (hours * msecPerHour);
- }
-
- if (isNumeric(minutes)) {
- this.msecs += (minutes * msecPerMinute);
- }
-
- if (isNumeric(seconds)) {
- this.msecs += (seconds * msecPerSecond);
- }
-
- if (isNumeric(milliseconds)) {
- this.msecs += milliseconds;
- }
-}; |
Factory methods- -Helper methods for creating new TimeSpan objects
-from various criteria: milliseconds, seconds, minutes,
-hours, days, strings and other | |
function fromMilliseconds (milliseconds)- -@milliseconds {Number} Amount of milliseconds for the new TimeSpan instance.- -Creates a new | exports.fromMilliseconds = function (milliseconds) {
- if (!isNumeric(milliseconds)) {
- return;
- }
-
- return new TimeSpan(milliseconds, 0, 0, 0, 0);
-} |
function fromSeconds (seconds)- -@milliseconds {Number} Amount of seconds for the new TimeSpan instance.- -Creates a new | exports.fromSeconds = function (seconds) {
- if (!isNumeric(seconds)) {
- return;
- }
-
- return new TimeSpan(0, seconds, 0, 0, 0);
-}; |
function fromMinutes (milliseconds)- -@milliseconds {Number} Amount of minutes for the new TimeSpan instance.- -Creates a new | exports.fromMinutes = function (minutes) {
- if (!isNumeric(minutes)) {
- return;
- }
-
- return new TimeSpan(0, 0, minutes, 0, 0);
-}; |
function fromHours (hours)- -@milliseconds {Number} Amount of hours for the new TimeSpan instance.- -Creates a new | exports.fromHours = function (hours) {
- if (!isNumeric(hours)) {
- return;
- }
-
- return new TimeSpan(0, 0, 0, hours, 0);
-}; |
function fromDays (days)- -@milliseconds {Number} Amount of days for the new TimeSpan instance.- -Creates a new | exports.fromDays = function (days) {
- if (!isNumeric(days)) {
- return;
- }
-
- return new TimeSpan(0, 0, 0, 0, days);
-}; |
function parse (str)- -@str {string} Timespan string to parse.- -Creates a new | exports.parse = function (str) {
- var match, milliseconds;
-
- function parseMilliseconds (value) {
- return value ? parseFloat('0' + value) * 1000 : 0;
- }
- |
If we match against a full TimeSpan: | if ((match = str.match(timeSpanWithDays))) {
- return new TimeSpan(parseMilliseconds(match[5]), match[4], match[3], match[2], match[1]);
- }
- |
If we match against a partial TimeSpan: | if ((match = str.match(timeSpanNoDays))) {
- return new TimeSpan(parseMilliseconds(match[4]), match[3], match[2], match[1], 0);
- }
-
- return null;
-};
-
-var months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; |
List of default singular time modifiers and associated -computation algoritm. Assumes in order, smallest to greatest -performing carry forward additiona / subtraction for each -Date-Time component. | var parsers = {
- 'milliseconds': {
- exp: /(\d+)milli[second]?[s]?/i,
- get: function (date) { return date.getMilliseconds(date) },
- set: function (val, date) { date.setMilliseconds(val) },
- compute: function (delta, date, computed) {
- var round = delta > 0 ? Math.floor : Math.ceil;
- if (delta) {
- computed.seconds += round.call(null, delta / 1000);
- computed.milliseconds += delta % 1000;
- }
-
- if (Math.abs(computed.milliseconds) >= 1000) {
- computed.seconds += round.call(null, computed.milliseconds / 1000)
- computed.milliseconds = computed.milliseconds % 1000;
- }
-
- return computed;
- }
- },
- 'seconds': {
- exp: /(\d+)second[s]?/i,
- get: function (date) { return date.getSeconds(date) },
- set: function (val, date) { date.setSeconds(val) },
- compute: function (delta, date, computed) {
- var round = delta > 0 ? Math.floor : Math.ceil;
- if (delta) {
- computed.minutes += round.call(null, delta / 60);
- computed.seconds += delta % 60;
- }
-
- if (Math.abs(computed.seconds) >= 60) {
- computed.minutes += round.call(null, computed.seconds / 60);
- computed.seconds = computed.seconds % 60;
- }
-
- return computed;
- }
- },
- 'minutes': {
- exp: /(\d+)minute[s]?/i,
- get: function (date) { return date.getMinutes(date) },
- set: function (val, date) { date.setMinutes(val) },
- compute: function (delta, date, computed) {
- var round = delta > 0 ? Math.floor : Math.ceil;
- if (delta) {
- computed.hours += round.call(null, delta / 60);
- computed.minutes += delta % 60;
- }
-
- if (Math.abs(computed.minutes) >= 60) {
- computed.hours += round.call(null, computed.minutes / 60);
- computed.minutes = computed.minutes % 60;
- }
-
- return computed;
- }
- },
- 'hours': {
- exp: /(\d+)hour[s]?/i,
- get: function (date) { return date.getHours(date) },
- set: function (val, date) { date.setHours(val) },
- compute: function (delta, date, computed) {
- var round = delta > 0 ? Math.floor : Math.ceil;
- if (delta) {
- computed.days += round.call(null, delta / 24);
- computed.hours += delta % 24;
- }
-
- if (Math.abs(computed.hours) >= 24) {
- computed.days += round.call(null, computed.hours / 24);
- computed.hours = computed.hours % 24;
- }
-
- return computed;
- }
- },
- 'days': {
- exp: /(\d+)day[s]?/i,
- get: function (date) { return date.getDate(date) },
- set: function (val, date) { date.setDate(val) },
- compute: function (delta, date, computed) {
- var sign = delta >= 0 ? 1 : -1,
- opsign = delta >= 0 ? -1 : 1,
- clean = 0,
- original = delta,
- month = computed.months,
- days = months[month];
-
- if (delta) {
- while (Math.abs(delta) >= days) {
- month += sign * 1;
- computed.months += sign * 1;
- delta += opsign * days;
-
- if (month < 0) { month = 11 }
- else if (month > 11) { month = 0 }
-
- days = months[month];
- }
-
- computed.days += (sign * delta);
- }
-
- if (computed.days < 0) {
- clean = -1;
- }
- else if (computed.days > months[computed.months]) {
- clean = 1;
- }
-
- if (clean !== 0) {
- computed.months += clean;
- if (computed.months < 0) { computed.months = 11 }
- else if (computed.months > 11) { computed.months = 0 }
- computed.days = months[computed.months] + computed.days;
- }
-
- return computed;
- }
- },
- 'months': {
- exp: /(\d+)month[s]?/i,
- get: function (date) { return date.getMonth(date) },
- set: function (val, date) { date.setMonth(val) },
- compute: function (delta, date, computed) {
- var round = delta > 0 ? Math.floor : Math.ceil;
- if (delta) {
- computed.years += round.call(null, delta / 12);
- computed.months += delta % 12;
- }
-
- if (computed.months > 11) {
- computed.years += Math.floor((computed.months + 1) / 12);
- computed.months = ((computed.months + 1) % 12) - 1;
- }
-
- return computed;
- }
- },
- 'years': {
- exp: /(\d+)year[s]?/i,
- get: function (date) { return date.getFullYear(date) },
- set: function (val, date) { date.setFullYear(val) },
- compute: function (delta, date, computed) {
- if (delta) {
- computed.years += delta;
- }
-
- return computed;
- }
- }
-}; |
Compute the list of parser names for -later use. | var parserNames = Object.keys(parsers); |
function parseDate (str)- -@str {string} String to parse into a date- -Parses the specified liberal Date-Time string according to -ISO8601 and: - -
Valid modifiers for the more liberal Date-Time string(s): - - | exports.parseDate = function (str) {
- var simple = Date.parse(str),
- iso = '^([^Z]+)',
- zulu = 'Z([\\+|\\-])?',
- diff = {},
- base,
- sign,
- complex,
- inspect,
- dateTime,
- modifiers;
-
- if (/now/i.test(str)) {
- iso = '^(NOW)';
- zulu = zulu.replace(/Z/, 'NOW');
- } |
If Date string supplied actually conforms -to UTC Time (ISO8601), return a new Date. | if (!isNaN(simple)) {
- return new Date(simple);
- }
- |
Create the | parserNames.forEach(function (group) {
- zulu += '(\\d+[a-zA-Z]+)?';
- });
- |
Parse the | dateTime = str.match(new RegExp(iso, 'i'));
- modifiers = str.match(new RegExp(zulu, 'i'));
- |
If there was no match on either part then -it must be a bad value. | if (!dateTime || !modifiers) {
- return null;
- }
- |
Create a new | base = /now/i.test(dateTime[1]) ? Date.now() : Date.parse(dateTime[1]);
- complex = new Date(base);
- sign = modifiers[1] === '+' ? 1 : -1;
- |
Parse the individual component spans (months, years, etc)
-from the modifier strings that we parsed from the end
-of the target | modifiers.slice(2).filter(Boolean).forEach(function (modifier) {
- parserNames.forEach(function (name) {
- var match;
- if (!(match = modifier.match(parsers[name].exp))) {
- return;
- }
-
- diff[name] = sign * parseInt(match[1], 10);
- })
- });
- |
Compute the total | var computed = {
- milliseconds: complex.getMilliseconds(),
- seconds: complex.getSeconds(),
- minutes: complex.getMinutes(),
- hours: complex.getHours(),
- days: complex.getDate(),
- months: complex.getMonth(),
- years: complex.getFullYear()
- };
-
- parserNames.forEach(function (name) {
- computed = parsers[name].compute(diff[name], complex, computed);
- });
-
- return new Date(
- Date.UTC(
- computed.years,
- computed.months,
- computed.days,
- computed.hours,
- computed.minutes,
- computed.seconds,
- computed.milliseconds
- )
- );
-}; |
function fromDates (start, end, abs)- -@start {Date} Start date of the
-
- | exports.fromDates = function (start, end, abs) {
- if (!start instanceof Date) {
- start = exports.parseDate(start);
- }
-
- if (!end instanceof Date) {
- end = exports.parseDate(end);
- }
-
- var differenceMsecs = end.valueOf() - start.valueOf();
- if (abs) {
- differenceMsecs = Math.abs(differenceMsecs);
- }
-
- return new TimeSpan(differenceMsecs, 0, 0, 0, 0);
-}; |
Module Helpers- -Module-level helpers for various utilities such as: -instanceOf, parsability, and cloning. | |
function test (str)- -@str {string} String value to test if it is a TimeSpan- -Returns a value indicating if the specified string, | exports.test = function (str) {
- return timeSpanWithDays.test(str) || timeSpanNoDays.test(str);
-}; |
function instanceOf (timeSpan)- -@timeSpan {Object} Object to check TimeSpan quality.- -Returns a value indicating if the specified | exports.instanceOf = function (timeSpan) {
- return timeSpan instanceof TimeSpan;
-}; |
function clone (timeSpan)- -@timeSpan {TimeSpan} TimeSpan object to clone.- -Returns a new | exports.clone = function (timeSpan) {
- if (!(timeSpan instanceof TimeSpan)) {
- return;
- }
-
- return exports.fromMilliseconds(timeSpan.totalMilliseconds());
-}; |
Addition- -Methods for adding | |
function add (timeSpan)- -@timeSpan {TimeSpan} TimeSpan to add to this instance- -Adds the specified | TimeSpan.prototype.add = function (timeSpan) {
- if (!(timeSpan instanceof TimeSpan)) {
- return;
- }
-
- this.msecs += timeSpan.totalMilliseconds();
-}; |
function addMilliseconds (milliseconds)- -@milliseconds {Number} Number of milliseconds to add.- -Adds the specified | TimeSpan.prototype.addMilliseconds = function (milliseconds) {
- if (!isNumeric(milliseconds)) {
- return;
- }
-
- this.msecs += milliseconds;
-}; |
function addSeconds (seconds)- -@seconds {Number} Number of seconds to add.- -Adds the specified | TimeSpan.prototype.addSeconds = function (seconds) {
- if (!isNumeric(seconds)) {
- return;
- }
-
- this.msecs += (seconds * msecPerSecond);
-}; |
function addMinutes (minutes)- -@minutes {Number} Number of minutes to add.- -Adds the specified | TimeSpan.prototype.addMinutes = function (minutes) {
- if (!isNumeric(minutes)) {
- return;
- }
-
- this.msecs += (minutes * msecPerMinute);
-}; |
function addHours (hours)- -@hours {Number} Number of hours to add.- -Adds the specified | TimeSpan.prototype.addHours = function (hours) {
- if (!isNumeric(hours)) {
- return;
- }
-
- this.msecs += (hours * msecPerHour);
-}; |
function addDays (days)- -@days {Number} Number of days to add.- -Adds the specified | TimeSpan.prototype.addDays = function (days) {
- if (!isNumeric(days)) {
- return;
- }
-
- this.msecs += (days * msecPerDay);
-}; |
Subtraction- -Methods for subtracting | |
function subtract (timeSpan)- -@timeSpan {TimeSpan} TimeSpan to subtract from this instance.- -Subtracts the specified | TimeSpan.prototype.subtract = function (timeSpan) {
- if (!(timeSpan instanceof TimeSpan)) {
- return;
- }
-
- this.msecs -= timeSpan.totalMilliseconds();
-}; |
function subtractMilliseconds (milliseconds)- -@milliseconds {Number} Number of milliseconds to subtract.- -Subtracts the specified | TimeSpan.prototype.subtractMilliseconds = function (milliseconds) {
- if (!isNumeric(milliseconds)) {
- return;
- }
-
- this.msecs -= milliseconds;
-}; |
function subtractSeconds (seconds)- -@seconds {Number} Number of seconds to subtract.- -Subtracts the specified | TimeSpan.prototype.subtractSeconds = function (seconds) {
- if (!isNumeric(seconds)) {
- return;
- }
-
- this.msecs -= (seconds * msecPerSecond);
-}; |
function subtractMinutes (minutes)- -@minutes {Number} Number of minutes to subtract.- -Subtracts the specified | TimeSpan.prototype.subtractMinutes = function (minutes) {
- if (!isNumeric(minutes)) {
- return;
- }
-
- this.msecs -= (minutes * msecPerMinute);
-}; |
function subtractHours (hours)- -@hours {Number} Number of hours to subtract.- -Subtracts the specified | TimeSpan.prototype.subtractHours = function (hours) {
- if (!isNumeric(hours)) {
- return;
- }
-
- this.msecs -= (hours * msecPerHour);
-}; |
function subtractDays (days)- -@days {Number} Number of days to subtract.- -Subtracts the specified | TimeSpan.prototype.subtractDays = function (days) {
- if (!isNumeric(days)) {
- return;
- }
-
- this.msecs -= (days * msecPerDay);
-}; |
Getters- -Methods for retrieving components of a | |
function totalMilliseconds (roundDown)- -@roundDown {boolean} Value indicating if the value should be rounded down.- -Returns the total number of milliseconds for this instance, rounding down
-to the nearest integer if | TimeSpan.prototype.totalMilliseconds = function (roundDown) {
- var result = this.msecs;
- if (roundDown === true) {
- result = Math.floor(result);
- }
-
- return result;
-}; |
function totalSeconds (roundDown)- -@roundDown {boolean} Value indicating if the value should be rounded down.- -Returns the total number of seconds for this instance, rounding down
-to the nearest integer if | TimeSpan.prototype.totalSeconds = function (roundDown) {
- var result = this.msecs / msecPerSecond;
- if (roundDown === true) {
- result = Math.floor(result);
- }
-
- return result;
-}; |
function totalMinutes (roundDown)- -@roundDown {boolean} Value indicating if the value should be rounded down.- -Returns the total number of minutes for this instance, rounding down
-to the nearest integer if | TimeSpan.prototype.totalMinutes = function (roundDown) {
- var result = this.msecs / msecPerMinute;
- if (roundDown === true) {
- result = Math.floor(result);
- }
-
- return result;
-}; |
function totalHours (roundDown)- -@roundDown {boolean} Value indicating if the value should be rounded down.- -Returns the total number of hours for this instance, rounding down
-to the nearest integer if | TimeSpan.prototype.totalHours = function (roundDown) {
- var result = this.msecs / msecPerHour;
- if (roundDown === true) {
- result = Math.floor(result);
- }
-
- return result;
-}; |
function totalDays (roundDown)- -@roundDown {boolean} Value indicating if the value should be rounded down.- -Returns the total number of days for this instance, rounding down
-to the nearest integer if | TimeSpan.prototype.totalDays = function (roundDown) {
- var result = this.msecs / msecPerDay;
- if (roundDown === true) {
- result = Math.floor(result);
- }
-
- return result;
-}; |
@milliseconds- -Returns the length of this | TimeSpan.prototype.__defineGetter__('milliseconds', function () {
- return this.msecs % 1000;
-}); |
@seconds- -Returns the length of this | TimeSpan.prototype.__defineGetter__('seconds', function () {
- return Math.floor(this.msecs / msecPerSecond) % 60;
-}); |
@minutes- -Returns the length of this | TimeSpan.prototype.__defineGetter__('minutes', function () {
- return Math.floor(this.msecs / msecPerMinute) % 60;
-}); |
@hours- -Returns the length of this | TimeSpan.prototype.__defineGetter__('hours', function () {
- return Math.floor(this.msecs / msecPerHour) % 24;
-}); |
@days- -Returns the length of this | TimeSpan.prototype.__defineGetter__('days', function () {
- return Math.floor(this.msecs / msecPerDay);
-}); |
Instance Helpers- -Various help methods for performing utilities -such as equality and serialization | |
function equals (timeSpan)- -@timeSpan {TimeSpan} TimeSpan instance to assert equal- -Returns a value indicating if the specified | TimeSpan.prototype.equals = function (timeSpan) {
- if (!(timeSpan instanceof TimeSpan)) {
- return;
- }
-
- return this.msecs === timeSpan.totalMilliseconds();
-}; |
function toString ()- -Returns a string representation of this | TimeSpan.prototype.toString = function () {
- if (!this.format) {
- return this._format();
- };
-
- return this.format(this);
-}; |
@private function _format ()- -Returns the default string representation of this instance. | TimeSpan.prototype._format = function () {
- return [
- this.days,
- this.hours,
- this.minutes,
- this.seconds + '.' + this.milliseconds
- ].join(':')
-}; |
@private function isNumeric (input)- -@input {Number} Value to check numeric quality of.- -Returns a value indicating the numeric quality of the
-specified | function isNumeric (input) {
- return input && !isNaN(parseFloat(input)) && isFinite(input);
-};
-
- |
pkginfo.js | |
---|---|
/*
- * pkginfo.js: Top-level include for the pkginfo module
- *
- * (C) 2011, Charlie Robbins
- *
- */
-
-var fs = require('fs'),
- path = require('path'); | |
function pkginfo ([options, 'property', 'property' ..])- -@pmodule {Module} Parent module to read from.- -@options {Object|Array|string} Optional Options used when exposing properties.- -@arguments {string...} Optional Specified properties to expose.- -Exposes properties from the package.json file for the parent module on -it's exports. Valid usage: - -
| var pkginfo = module.exports = function (pmodule, options) {
- var args = [].slice.call(arguments, 2).filter(function (arg) {
- return typeof arg === 'string';
- });
- |
Parse variable arguments | if (Array.isArray(options)) { |
If the options passed in is an Array assume that -it is the Array of properties to expose from the -on the package.json file on the parent module. | options = { include: options };
- }
- else if (typeof options === 'string') { |
Otherwise if the first argument is a string, then -assume that it is the first property to expose from -the package.json file on the parent module. | options = { include: [options] };
- }
- |
Setup default options | options = options || { include: [] };
-
- if (args.length > 0) { |
If additional string arguments have been passed in -then add them to the properties to expose on the -parent module. | options.include = options.include.concat(args);
- }
-
- var pkg = pkginfo.read(pmodule, options.dir).package;
- Object.keys(pkg).forEach(function (key) {
- if (options.include.length > 0 && !~options.include.indexOf(key)) {
- return;
- }
-
- if (!pmodule.exports[key]) {
- pmodule.exports[key] = pkg[key];
- }
- });
-
- return pkginfo;
-}; |
function find (dir)- -@pmodule {Module} Parent module to read from.- -@dir {string} Optional Directory to start search from.- -Searches up the directory tree from | pkginfo.find = function (pmodule, dir) {
- dir = dir || pmodule.filename;
- dir = path.dirname(dir);
-
- var files = fs.readdirSync(dir);
-
- if (~files.indexOf('package.json')) {
- return path.join(dir, 'package.json');
- }
-
- if (dir === '/') {
- throw new Error('Could not find package.json up from: ' + dir);
- }
-
- return pkginfo.find(dir);
-}; |
function read (pmodule, dir)- -@pmodule {Module} Parent module to read from.- -@dir {string} Optional Directory to start search from.- -Searches up the directory tree from | pkginfo.read = function (pmodule, dir) {
- dir = pkginfo.find(pmodule, dir);
-
- var data = fs.readFileSync(dir).toString();
-
- return {
- dir: dir,
- package: JSON.parse(data)
- };
-}; |
Call | pkginfo(module, {
- dir: __dirname,
- include: ['version'],
- target: pkginfo
-});
-
- |